首页 文章

RxJs:如何有条件地链接可观察的BehaviorSubject?

提问于
浏览
4

我有一个可观察的数据服务(UserService),它返回当前登录的用户 . 我遵循了本教程 - https://coryrylan.com/blog/angular-observable-data-services,它描述了使用BehaviorSubject立即返回默认的currentUser,然后在加载或更改后发出真正的currentUser . 服务基本上就像这样......

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重新加载整个水疗中心时,我遇到了问题 . 当消费组件订阅UserService上的currentUser时,它会立即收到默认用户,而UserService等待api调用以接收实际用户 . api调用完成的那一刻,真实用户由UserService发出,所有订阅者都获得真实用户 . 但是,BehaviorSubject发出的第一个值是默认值,它的id始终为“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;
  });

1 回答

  • 5

    如果要忽略没有 id 的用户实例,请使用filter operator

    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;
      });
    

    关于"why the subscribe never fires",可能是由于未定义 id 引起的错误 . 您只将 next 函数传递给 subscribe ,因此任何错误都将无法处理 . 如果发生错误,observable将终止并取消订阅任何订阅者 - 因为这是observables的行为 - 因此将不会收到任何具有已定义 id 属性的后续用户 .

相关问题