RxJs: How to conditionally track a BehaviorSubject chain?

I have an observable data service (UserService) that returns a registered user. I followed this tutorial - https://coryrylan.com/blog/angular-observable-data-services , which describes how to use a BehaviorSubject to immediately return the currentUser to default, and then release the real currentUser after it is downloaded or modified. The service is basically like that ...

private _currentUser: BehaviorSubject<User> = new BehaviorSubject(new User());
public currentUser: Observable<User> = this._currentUser.asObservable();

constructor(private http: Http) {}

loadUser() { // app.component onInit and login component call this
  return this.http.get('someapi.com/getcurrentuser')
  .map(response => <User>this.extractData(response))
  .do(
    (user) => {
      this.dataStore.currentUser = user;
      this._currentUser.next(Object.assign(new User(), this.dataStore).currentUser);
    },
    (error) => this.handleError(error)
  )
  .catch(error -> this.handleError(error));
}

, F5, -. currentUser UserService, , UserService api . , api, UserService, . , BehaviorSubject, "undefined", api. , , , user.id, , .

, - , . concatMap, , . , , . , , , , Observables.

this.userService.currentUser
  .flatMap((user) => {
    this.user = user;
    // Need to NOT call this if the user does not have an id!!!
    this.someOtherService.getSomethingElse(user.id); // user.id is always undefined the first time
  })
  .subscribe((somethingElse) => {
    // This never gets called, even after the real user is emitted by the UserService 
    // and I see the getSomethingElse() call above get executed with a valid user.id
    this.somethingElse = somethingElse;
  });
+4
1

, id, filter:

import 'rxjs/add/operator/filter';

this.userService.currentUser
  .filter((user) => Boolean(user.id))
  .flatMap((user) => {
    this.user = user;
    this.someOtherService.getSomethingElse(user.id);
  })
  .subscribe((somethingElse) => {
    this.somethingElse = somethingElse;
  });

" ", , - , undefined id. next subscribe, . , - - , - id .

+5

Source: https://habr.com/ru/post/1673173/


All Articles