我有一个请求,看起来像这样:
private getData(param) {
const url = (name: string) =>
`https://website.com/${name}/data`;
return this.http.get<Data>(url(param));
}
当请求返回错误时,我想用另一个参数重试。你怎么能那样做?
我能够捕捉到像这样的错误
private getData(param) {
const url = (name: string) =>
`https://website.com/${name}/data`;
return this.http.get<Data>(url(param)).pipe(
catchError(error => of(error))
);
}
但是,您将如何使用不同的url重试?
catchError
的返回值是observable
。如果你只是想提出一个新的请求,你可以用你的新请求替换可观察到的错误。就像这样。
const example = source.pipe(
catchError(val => {
return of(`new request result`)
}));
//output: 'new request result'
const subscribe = example.subscribe(val => console.log(val));
不确定,但你能这样尝试吗?
private getData(param) {
const url = (name: string) =>
`https://website.com/${name}/data`;
const anotherUrl = (name: string) =>
`https://website.com/${name}/data`;
return this.http.get<Data>(url(param)).pipe(
catchError(error => of(error){
this.http.get<Data>(anotherUrl(param)).pipe(
catchError(error => of(error))
})
);
}
如果我是你,我会试试这个
class UserService {
private getData(param, tried=3) {
const url = (name: string) => {
`https:///website.com/${name}/data`;
}
return this.http.get<Data>(url(param)).pipe(catchError(error => {
if (tried < 0) {
throw error;
}
// assign name, param's property as a new value
param.name = 'newName';
// then, call again with param with another name
// while tried counter to be 0
this.getData(param, tried - 1);
}));
}
}
- 在
getData
方法中添加一个新参数tried
,以处理重试的无限循环。并将它的默认值设置为3(可能是5、7,还有什么你喜欢的( - 使用您的方法,该方法使用
NestJS
和.pipe
的http
方法 - 然后,如果这个请求出现错误,请使用另一个名称重试续订的参数,比如分配我写的
param.name = 'newName'
- 使用
tried
参数中的dicsount-1递归调用此getData
方法
愿这对你有所帮助。