how do i intercept an observable to get the value and still return an observable?

Viewed 180

I was writing a sign in function in angular service that returns an observable. I want to intercept the stream, get the value and set to variable without subscribing. i tried to use pipe and map operator and didn't work. what's the best approach to do this?

import { Observable, of } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';
 
@Injectable({
  providedIn: 'root',
})
export class AppService {
  signInUrl: string = 'http://localhost:3000/api/v1/users/login';
  user: any;
  constructor(private _http: HttpClient) {}
 
  getUser(): Observable<any> {
    return of(this.user);
  }
 
 signIn(obj): Observable<any> {
    return this._http.post(this.signInUrl, obj).pipe(
      map((u) => {
        this.user = u;
      })
    );
  }
 
  logOut(): void {
    this.user = null;
  }
}
2 Answers

Your code should work, its just not getting triggered. I think you forgot to subscribe to the method.

For example: signIn(obj).subscribe(); should do the trick.

I think what you have to do is change 'map' with 'tap'

Related