微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Angular Multiple Http Call grouping error to parent observable method

如何解决Angular Multiple Http Call grouping error to parent observable method

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

// 组件调用

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

//服务调用

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

switch(documentType){

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

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

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

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

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

谢谢

解决方法

查看 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,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`);
    }
  }
});

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。