简体   繁体   English

Angular 订阅不可分配给可观察的

[英]Angular subscription is not assignable to observable

I need help creating a function that gets the categories from my API and also checks for status of the call.我需要帮助创建一个 function,它从我的 API 获取类别并检查通话状态。 I have written my function like the code bellow but it keep showing me the bellow error:我已经像下面的代码一样编写了我的 function 但它一直向我显示以下错误:

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

Here is the code of my function:这是我的 function 的代码:

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

You should not use .subscribe inside a subscription.您不应在订阅中使用.subscribe .subscribe returns a Subscription which can't be assigned to the Observable that a switchMap should return. .subscribe返回一个Subscription ,它不能分配给switchMap应该返回的Observable

Use catchError to to handle the error case and a map to handle the success case.使用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)
  )
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM