![](/img/trans.png)
[英]Modifying object at service layer in angular2: Subscription is not assignable to the type observable
[英]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.