typescript Angular 订阅不能分配给可观察项

bsxbgnwa  于 2022-12-14  发布在  TypeScript
关注(0)|答案(1)|浏览(118)

我需要帮助创建一个函数,从我的API获取类别,并检查调用的状态。我已经编写了我的函数,如下面的代码,但它一直显示我下面的错误:

Argument of type '(token: GetResult) => Subscription' is not assignable to parameter of type '(value: GetResult, index: number) => ObservableInput<any>'

下面是函数的代码:

getCategories() {
  return from(Preferences.get({ key: "TOKEN_KEY" })).pipe(
    switchMap((token) => {
      const headers = new HttpHeaders().set(
        "Authorization",
        `Bearer ${token.value}`
      );
      return this.httpClient
        .get(`${environment.apiUrl}categories`, {
          headers,
          observe: "response",
        })
        .subscribe(
          (res) => {
            return res.body;
          },
          (error) => {
            console.log(error.status);
            if (error.status === 400) {
              console.log(error.error.message);
            }
            if (error.status === 401) {
              this.authService.logout();
              this.router.navigateByUrl("/login", { replaceUrl: true });
            }
          }
        );
    })
  );
}
bvhaajcl

bvhaajcl1#

您不应该在订阅内使用.subscribe.subscribe会传回Subscription,而Subscription无法指派给switchMap应该传回的Observable
使用catchError处理错误情况,使用map处理成功情况。

getCategories() {
  return from(Preferences.get({ key: 'TOKEN_KEY' })).pipe(
    switchMap(token => {
      const headers = new HttpHeaders().set('Authorization', `Bearer ${token.value}`);
      return this.httpClient.get(
        `${environment.apiUrl}categories`, 
        { headers, observe: 'response' }
      )
    }),
    catchError(error => {
      console.log(error.status);
      if (error.status === 400) {
        console.log(error.error.message);
      }
      if (error.status === 401) {
        this.authService.logout();
        this.router.navigateByUrl('/login', { replaceUrl: true });
      }

      return EMPTY
    }),
    map(res => res.body)
  )
};

相关问题