我有一个看起来像这样的请求:
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重试呢?
发布于 2021-05-02 08:01:57
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));
发布于 2021-05-02 07:51:18
不知道,但你能这样试一下吗?
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))
})
);
}
发布于 2021-05-02 12:47:01
如果我是你,我会这样尝试。
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);
}));
}
}
tried
添加到getData
方法,以处理无限循环的重试。并将其缺省值设置为3(可能是5、7,其他您喜欢的值),并使用您的方法,如果此请求出错,请使用NestJS
和.pipe
.http
方法,重试使用另一个名称更新的参数,如分配我编写的param.name = 'newName'
。tried
参数中的dicsount -1递归调用此getData
方法。<代码>H217<代码>G218愿这对你有所帮助。
https://stackoverflow.com/questions/67351713
复制相似问题