簡體   English   中英

Angular 訂閱不可分配給可觀察的

[英]Angular subscription is not assignable to observable

我需要幫助創建一個 function,它從我的 API 獲取類別並檢查通話狀態。 我已經像下面的代碼一樣編寫了我的 function 但它一直向我顯示以下錯誤:

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

這是我的 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 });
            }
          }
        );
    })
  );
}

您不應在訂閱中使用.subscribe .subscribe返回一個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)
  )
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM