【问题标题】:How to retry with different url if request returns an error如果请求返回错误,如何使用不同的 url 重试
【发布时间】:2021-07-24 20:22:24
【问题描述】:

我的请求如下所示:

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

【问题讨论】:

    标签: angular rxjs nestjs


    【解决方案1】:

    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));
    

    【讨论】:

      【解决方案2】:

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

       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))
             })
          );
        }
      

      【讨论】:

        【解决方案3】:

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

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

        希望对您有所帮助。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-12-24
          • 1970-01-01
          • 2022-07-31
          • 1970-01-01
          • 2022-06-23
          • 2022-10-24
          • 2021-11-14
          • 1970-01-01
          相关资源
          最近更新 更多