【问题标题】:Best method to "fork" observable“分叉”可观察的最佳方法
【发布时间】:2017-12-02 12:17:22
【问题描述】:

每次 http auth API 返回授权用户时,我都需要设置currentUser: BehaviorSubject<>()。现在我正在使用do 将新用户发送到BehaviorSubject,但完成这样的任务似乎是一种肮脏的方式。

是否有 fork 方法或类似的方法可以更新观察者并返回原始的 observable?

我有什么

public currentUser: BehaviorSubject<any> = new BehaviorSubject<any>(null);

authUser(email: String, password: String) {
  return this.http.post('api.com/auth', {
    email: email,
    password: password
  })
  .do(user => this.currentUser.next(user))
}

我想要什么

return this.http.post('api.com/auth', {
  email: email,
  password: password
})
.fork(this.currentUser)

【问题讨论】:

  • 但更新Subject 的唯一方法是通过next() 方法,不是吗
  • 你需要使用behaviorSubject为什么不能直接从http方法使用observable?

标签: angular rxjs rxjs5


【解决方案1】:

有不同的方法来解决这个问题,但我认为你应该使用subscribe 而不是do 并且authUser 不应该返回任何东西。为什么有两种方法可以访问同一个东西(当前用户)?

//private field and getter are optional but allows you to expose the
//field as an observable and not a subject
private _currentUser: BehaviorSubject<any> = new BehaviorSubject<any>(null);

get currentUser(): Observable<any> {
  return this._currentUser;
}

authUser(email: String, password: String): void {
  this.http.post('api.com/auth', {
    email: email,
    password: password
  })
  .subscribe(user => this._currentUser.next(user))
}

如果您想进行清理(这是一个异步操作,因此您可能想知道何时完成),您可以这样做:

authUser(email: String, password: String): Observable<void> {
  let requestObs = this.http.post('api.com/auth', {
    email: email,
    password: password
  }).shareReplay();
  requestObs.subscribe(user => this._currentUser.next(user));
  return requestObs.map(user => null);
}

当然,如果你真的想要返回值,你可以删除最后一个 map 语句。最后,它与您的do 并没有太大区别。

【讨论】:

  • 嗯,我认为返回一个 auth observable 是有意义的,因为您可以在用户登录后为他们执行任何清理/转换,并确保该操作是从该确切的身份验证周期产生的。不过谢谢,我只是认为用例可能足够普遍,可以有自己的解决方案,显然不是
  • 抱歉,我添加了更多示例,但我认为没有任何运算符具有您想要的语法。 shareReplay 的最终结果与do 基本相同,只是调用者不必订阅即可触发调用。
猜你喜欢
  • 2023-03-13
  • 1970-01-01
  • 2022-12-15
  • 2014-10-13
  • 2021-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-09
相关资源
最近更新 更多