【问题标题】:How to return an observabe based on the result of another observabe in angular 2/4/5如何根据角度 2/4/5 中另一个可观察对象的结果返回可观察对象
【发布时间】:2018-01-03 13:41:34
【问题描述】:

您好,我正在制作一个 Angular 5 的登录页面。我的方法如下:

login(context: LoginContext): Observable<number> {
let profileId: number;

this.http.post<AuthRes>(SERVER_API_URL + "api/authenticate", context).subscribe(authRes => {
  profileId = authRes.profileId;
  this.tokenService.setToken(authRes.token, context.rememberMe);
});

return of(profileId);
}

我的问题是有时,profileId 在第一个 observable 完成工作之前返回为 observable,当我尝试验证用户是否登录时,我得到了错误的结果。

我只想在我的第一个 observable 执行后返回 profileId。

谢谢

【问题讨论】:

  • 订阅无法返回

标签: angular rxjs observable


【解决方案1】:
login(context: LoginContext): Observable<number> {
    return this.http.post<AuthRes>(`${SERVER_API_URL}api/authenticate`, context)
         .do(authRes => this.tokenService.setToken(authRes.token, context.rememberMe))
         .map(authRes => authRes.profileId);
}

【讨论】:

  • 感谢它的工作,我只需要将这一行添加到我的导入中:import 'rxjs/add/operator/do';
  • 注意:“do”不会根据另一个 observable 的结果返回 observable,“do”只会在 observable 完成时创建函数
猜你喜欢
  • 2017-07-12
  • 2019-02-18
  • 2021-10-31
  • 2020-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-19
相关资源
最近更新 更多