【问题标题】:Catching httpClient response inside a service with rxjs使用 rxjs 在服务中捕获 httpClient 响应
【发布时间】:2019-06-30 19:23:10
【问题描述】:

我有一个 LoginComponent(用于凭据的表单)和一个 LoginService,用于使用 httpClient 调用我的 api。

通常在我的服务中我会返回调用,以便我可以在我的组件中订阅它。

例如:

doSomething() {
    return this.http.post<any>(...);
}

这里的问题是我需要在我的组件和服务中订阅调用,因为我想在那里处理存储。

我在教程中找到了这个解决方案,但我认为这不是最合适的方法,也许使用 rxjs 管道有更好的解决方案。

授权服务:

login(userName: string, password: string, onSuccess: () => void, onError: (error) => void) {

  this.http.post("https://localhost:5001/api/auth/login", {userName: userName, password: password})
    .subscribe(response => {
      let token = (<any>response).token;
      localStorage.setItem("jwt", token);
      this.readUserFromLocalStorage();

      onSuccess();
    }, err => {
      onError(err);
    });
}

在我的组件内部

login() {
  this.auth.login(this.userName, this.password,
    () => this.router.navigateByUrl('/'),
    (error) => this.invalidLogin = true
  );
}

【问题讨论】:

标签: angular rxjs httpclient


【解决方案1】:

在您的身份验证服务中,您可以在pipe 中使用tap

tap 是一种非常好的方法,可以在不修改响应的情况下对响应进行处理。 (如果您确实需要在到达组件的途中对其进行修改,那么您可能应该使用 map 函数。

  this.http.post("https://localhost:5001/api/auth/login", {userName: userName, password: password})
    .pipe(tap(response => {
      let token = (<any>response).token;
      localStorage.setItem("jwt", token);
      this.readUserFromLocalStorage();
     }));
}

然后你就可以订阅你的组件了。

login() {
  this.auth.login(this.userName, this.password).subscribe(() => {
    this.router.navigateByUrl('/')
  },
    (error) => this.invalidLogin = true
}

这样你就不需要回调你的服务了!希望这会有所帮助。

【讨论】:

  • 正是我想要的。谢谢詹姆斯!
  • 太棒了!很高兴我能帮助你。如果您能接受它作为最佳答案,那就太棒了:)
猜你喜欢
  • 2017-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多