我得到了一个意外的 Observable(随机)作为响应
res
(预期结果是一个对象数组):
this.api[op.type](op.endpoint,op.body, op.token).pipe(
take(1),
tap(async res=>{
try{
if (res){ //getting Observable here
//do something with res
}
}catch(err){
console.log(err)
}
}),
catchError(async (err)=>{
//more error handling
})
我的
api['post']
是这样的:
post(endpoint: string, body: any, token? : string, reqOpts?: any, url_alt?: any) {
this.set_headers(token);
if (!reqOpts) reqOpts = {};
this.headers.append({"Content-Type": "application/json"});
reqOpts.headers = this.headers;
return this.http.post(this.url + endpoint, body, reqOpts).pipe(
timeout(105000),
retry(3),
catchError(async (error)=>{
return throwError(error)
})
);
}
}
非常感谢有关此处问题的任何指导
异步行是
catchError
帖子块中的问题,当我在函数 Observable 返回之前添加异步时,否则它工作正常!
服务
import { Injectable } from '@angular/core';
import { of, retry, take, throwError, timeout } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';
@Injectable({
providedIn: 'root',
})
export class TestService {
constructor() {}
post(
endpoint: string,
body: any,
token?: string,
reqOpts?: any,
url_alt?: any
) {
// this.set_headers(token);
if (!reqOpts) reqOpts = {};
// this.headers.append({"Content-Type": "application/json"});
// reqOpts.headers = this.headers;
return throwError('test') // this.http.post(this.url + endpoint, body, reqOpts) // mock http call!
.pipe(
timeout(105000),
retry(3),
catchError((error) => {
// <-- this line is the problem, when I add async before the function Observable gets returned, else it works fine!
return of(error);
})
);
}
postWrapper() {
return this.post('', null).pipe(
take(1),
tap(async (res) => {
try {
console.log('tap', res);
if (res) {
//getting Observable here
//do something with res
}
} catch (err) {
console.log('catch', err);
}
}),
catchError(async (err) => {
return of(err);
//more error handling
})
);
}
}