0

我有一个看起来像这样的请求:

  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 重试?

4

3 回答 3

2

的返回值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-02T00:01:56.517 回答
1

不确定,但你可以这样试试吗?

 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-01T23:51:17.773 回答
1

如果我是你,我会这样尝试

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);
    }));  
  }
}
  1. 为方法添加一个新参数triedgetData处理重试的无限循环。并将其默认值设置为 3(可能是 5、7,还有什么你喜欢的)
  2. 使用您的方法,该方法使用和的http方法。NestJS.pipe
  3. 然后如果这个请求出错了,用另一个名字重试更新的参数,就像param.name = 'newName'我写的赋值一样。
  4. getData使用参数中的 diccount -1 递归调用此方法tried

愿这对你有所帮助。

于 2021-05-02T04:47:00.693 回答