使用rxjs在服务内部捕获httpClient响应

时间:2019-06-30 19:23:10

标签: angular rxjs httpclient

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

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

例如:

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

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

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

AuthService:

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

1 个答案:

答案 0 :(得分:1)

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

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
}

这样,您无需回调服务!希望这会有所帮助。

相关问题