【问题标题】:Angular Multiple Http Call grouping error to parent observable methodAngular Multiple Http Call 对父可观察方法的分组错误
【发布时间】:2021-05-31 15:51:57
【问题描述】:

我有一个关于多个 http 调用和在错误发生时捕获错误并能够在父组件上读取它们的问题。 我需要知道哪些调用失败,以便我可以在另一种方法上重试它们,但如果我在组件级别看不到它们,不知何故我不可能知道我需要重试哪个调用

// 组件调用

generateDocuments(documentType: DocumentType, validDocuments: DocumentTemplate): observable<any>{
return this.documentService.generateDocuments(clientId, ClientDescription,documentType, validDocuments)}

//服务调用:

generateDocuments(clientId: int, ClientDescription,documentType:DocumentType, validDocuments: DocumentTemplate): observable<any>{

switch(documentType){

documentType.Word:{
return this.getDocumentCall(clientId, ClientDescription, ...)}

documentType.Excel:{
return this.getDocumentCall(clientId, ClientDescription, ...)}
}

// 这行会根据调用完成的时间,一一抛出错误/成功

 private getDocumentCall(clientId: int, clientDescription: string, ....)
    {
    
    return forkjoin([1,2,4,4,5].map((documentId:number) => {
    
    this.http.get('uri'+documentId+'/'+clientId,headers..).pipe( catchError(error => {
                return of(error);
              });
    });

我的问题是我如何知道组件级别的调用成功或失败,或者能够将所有错误/响应冒泡到组件级别

谢谢

【问题讨论】:

    标签: angular typescript rxjs observable fork-join


    【解决方案1】:

    查看forkJoin here。我认为对你来说最好传入一个带有键值对的对象,这样你就可以更好地识别。

    按照你的方式,订阅时每次调用的顺序都是相同的(本质上它仍然在 [1, 2, 3, 4, 5] 中)。

    您的 catchError 捕获 API 调用的错误并为 subscribes 的任何人返回一个成功的错误对象。

    这样的事情应该可以帮助您入门:

    this.service.getDocumentCall(1, 'hello').subscribe(responses => {
      responses.forEach(response => {
         // check if the response is instance of HttpErrorResponse signalling an error
         if (response instanceof HttpErrorResponse) {
            console.log('This call failed');
         } else {
            console.log('This call succeeded');
         }
      });
    });
    

    编辑:

    试试这样的:

    private getDocumentCall(clientId: int, clientDescription: string, ....)
        {
          const calls = {};
          const ids = [1, 2, 3, 4, 5];
          
          // create the calls object
          ids.forEach(id => {
             calls[id] = this.http.get('uri' + id + '/' + clientId, headers...).pipe( catchError(error => {
                    return of(error);
                  });
          });
          return forkJoin(calls);
        });
    
    this.getDocumentCall(1, '2').subscribe(response => {
      // loop through object
      for (const key in response) {
        if (response[key] instanceof HttpErrorResponse) {
          console.log(`Call with id: ${key} failed`);
        } else {
          console.log(`Call with id: ${key} succeeded`);
        }
      }
    });
    

    【讨论】:

    • 那么我将在哪里循环遍历 ID?
    • 非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-12
    • 1970-01-01
    • 2023-04-10
    • 2015-08-11
    • 2019-09-09
    • 1970-01-01
    相关资源
    最近更新 更多