Node.js 返回自己的静态值(在可观察状态下)
在我的nest.js项目中,我对一个开放API执行get请求。如果API没有结果,我会得到HTTP状态400。在这种情况下,我想从Node.js 返回自己的静态值(在可观察状态下),node.js,typescript,observable,axios,nestjs,Node.js,Typescript,Observable,Axios,Nestjs,在我的nest.js项目中,我对一个开放API执行get请求。如果API没有结果,我会得到HTTP状态400。在这种情况下,我想从可观察对象返回一个空的静态对象 this.getData(data.title) .subscribe((resp) => { console.log(resp); }); 可观察 getData(title: string){ const AuthStr = 'Bearer '.conca
可观察对象
返回一个空的静态对象
this.getData(data.title)
.subscribe((resp) => {
console.log(resp);
});
可观察
getData(title: string){
const AuthStr = 'Bearer '.concat(API.TOKEN);
const requestOptions = {
headers: { Authorization: AuthStr }
};
const emptyResponse = {
"data": [{"id": ''}]
}
try {
return this.httpService.get(API.ID_URL + title, requestOptions);
} catch (error) {
if(error.response.status == 400){
return of(JSON.stringify(emptyResponse)); //this doesn't work
}
this.errorHandling(error);
}
}
对于
可观察对象
,您必须使用catchError
操作符,而不是try/catch:
this.httpService.get(API.ID_URL + title, requestOptions)
.pipe(catchError(err => {
if (err.response && err.response.status == 400) {
return of({});
} else {
this.errorHandling(err);
}
}));
async getData(title: string) {
^^^^^
// ...
try {
return await this.httpService.get(API.ID_URL + title, requestOptions).toPromise();
^^^^^ ^^^^^^^^^^^^
} catch (error) {
if(error.response.status == 400){
return emptyResponse;
^^^^^^^^^^^^^
}
this.errorHandling(error);
}
或者,您可以将
可观察的
转换为承诺
。使用async/await,然后可以使用try/catch:
this.httpService.get(API.ID_URL + title, requestOptions)
.pipe(catchError(err => {
if (err.response && err.response.status == 400) {
return of({});
} else {
this.errorHandling(err);
}
}));
async getData(title: string) {
^^^^^
// ...
try {
return await this.httpService.get(API.ID_URL + title, requestOptions).toPromise();
^^^^^ ^^^^^^^^^^^^
} catch (error) {
if(error.response.status == 400){
return emptyResponse;
^^^^^^^^^^^^^
}
this.errorHandling(error);
}
请注意,getData
现在返回一个Promise
而不是一个可观察的
,因此您必须更改调用该方法的位置