2

I am new to RxJS and I am trying to subscribe to an observable function in two different and I am wondering if there is a way to trigger a call from one of the functions can also change the outcome in the second file.

I have an action creator and authGuard subscribe to my loginService and I am trying the action creator will trigger once I call the login function from the auth guard.

action.js

    this.loginService.handleLogin(userId)
      .subscribe((data) => {
         console.log("response in action.js", response);
      },
      (e) => {
        console.log(e);
      });

authGuard.js

    this.loginService.handleLogin(userId)
      .subscribe((response) => {
        console.log("response in authGuard.js", response);
      }, (err) => {
        console.log("error", err);
      })

loginService.js

    handleLogin(userId) {
      const url = `api/user/${userId}`;
      return this.http.get(url, { headers: this.headers })
        .map((response: Response) => {
          return response.json();
        })
        .catch((e) => {
          return Observable.throw(e);
        });
    }

expectation:

I am expecting to get console.logs results in action.js and authGuard.js when I call handlLogin function of loginService from either file.

tsinat
  • 235
  • 1
  • 3
  • 16

2 Answers2

1

Each time you call handleLogin, a separate observable is being created and returned. So your two files are not subscribed to the same object.

Take a look at the answers here for how to structure your handleLogin implementation to fix this: What is the correct way to share the result of an Angular Http network call in RxJs 5?. Note in particular this answer about shareReplay() which is probably the better up to date answer though it's not the highest scored: https://stackoverflow.com/a/43943217/518955

Robert Levy
  • 28,747
  • 6
  • 62
  • 94
0

The HTTP observable makes an HTTP request for each subscriber. To share a single HTTP request for multiple observers, you need something like the share operator.

   export class FetchService {
    data$: Observable<any>;

    constructor(){
        this.data$ = this._http.request(this._url)
            .map((res:Response)=>res.json())
            .catch(this.errorHandler)
            .share();
    }

    getData(){
        return this.data$;
    }
}

Now the multiple observers will share the same observable.

This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.

Vikas
  • 11,859
  • 7
  • 45
  • 69