使用Angular';什么是HttpClient?

使用Angular';什么是HttpClient?,angular,async-await,observable,synchronous,angular-httpclient,Angular,Async Await,Observable,Synchronous,Angular Httpclient,我有以下类型的对象数组 处理详细信息.model.ts export class ProcessingDetails{ id: string; isProcessingOccured: boolean; isProcessingSuccessful:boolean; constructor(id,isProcessingOccured,isProcessingSuccessful) { this.id = id; t

我有以下类型的对象数组

处理详细信息.model.ts

export class ProcessingDetails{
     id: string;
     isProcessingOccured: boolean;
     isProcessingSuccessful:boolean;
     constructor(id,isProcessingOccured,isProcessingSuccessful) {
          this.id = id;
          this.isProcessingOccured = isProcessingOccured;
          this.isProcessingSuccessful = isProcessingSuccessful;
     }
}
@Injectable()
export class AutomatedBatchService {
     constructor(@Inject('baseUrl') private baseUrl: string, private httpClient: HttpClient) {}

     public triggerProcessing(batchDetails:ProcessingDetails) {
         return this.httpClient.post(`${this.baseUrl}`,batchDetails);
     }
}
import { Component } from "@angular/core";
@Component({
     selector: 'processing-test',
     templateUrl: './processing-test.component.html',
     styleUrls:['./processing-test.component.css'],
     providers: [AutomatedBatchService]
})
export class ProcessingTestComponent {
     constructor(private automatedBatchService: AutomatedBatchService) { }
     public isSuccess:boolean = true;
     public processingArray: Array<ProcessingDetails>= [];
     async startBatchRun() {
         for( var i = 0; i < this.processingArray.length; i++ ) {
              if(this.isSuccess){
                 await this.automatedBatchService.triggerProcessing(this.processingArray[i])
                 .toPromise()
                 .then(res => {
                     this.processingArray[i].isProcessingOccured = true
                     this.processingArray[i].isProcessingSuccessful = true
                 })
                 .catch(rej => {
                     this.isSuccess = false
                     this.processingArray[i].isProcessingOccured = true
                     this.processingArray[i].isProcessingSuccessful = false
                 });

             }else {
                 break;
             }            
         }
     }
}
数组是基于某些输入动态生成的。一旦生成了数组,它将如下所示

processingArray = [{id:1, isProcessingOccured: false, isProcessingSuccessful: false},
                   {id:2, isProcessingOccured: false, isProcessingSuccessful: false},
                   .....
                   {id:k, isProcessingOccured: false, isProcessingSuccessful: false}]
我有一个REST端点,它接受类型为ProcessingDetails的对象。以下是我的服务代码

自动批处理服务.ts

export class ProcessingDetails{
     id: string;
     isProcessingOccured: boolean;
     isProcessingSuccessful:boolean;
     constructor(id,isProcessingOccured,isProcessingSuccessful) {
          this.id = id;
          this.isProcessingOccured = isProcessingOccured;
          this.isProcessingSuccessful = isProcessingSuccessful;
     }
}
@Injectable()
export class AutomatedBatchService {
     constructor(@Inject('baseUrl') private baseUrl: string, private httpClient: HttpClient) {}

     public triggerProcessing(batchDetails:ProcessingDetails) {
         return this.httpClient.post(`${this.baseUrl}`,batchDetails);
     }
}
import { Component } from "@angular/core";
@Component({
     selector: 'processing-test',
     templateUrl: './processing-test.component.html',
     styleUrls:['./processing-test.component.css'],
     providers: [AutomatedBatchService]
})
export class ProcessingTestComponent {
     constructor(private automatedBatchService: AutomatedBatchService) { }
     public isSuccess:boolean = true;
     public processingArray: Array<ProcessingDetails>= [];
     async startBatchRun() {
         for( var i = 0; i < this.processingArray.length; i++ ) {
              if(this.isSuccess){
                 await this.automatedBatchService.triggerProcessing(this.processingArray[i])
                 .toPromise()
                 .then(res => {
                     this.processingArray[i].isProcessingOccured = true
                     this.processingArray[i].isProcessingSuccessful = true
                 })
                 .catch(rej => {
                     this.isSuccess = false
                     this.processingArray[i].isProcessingOccured = true
                     this.processingArray[i].isProcessingSuccessful = false
                 });

             }else {
                 break;
             }            
         }
     }
}
我的目标是以同步方式为
processingArray
的每个元素调用
triggerProcessing
。如果对
processingArray
的一个对象调用
triggerProcessing
,我们将该特定对象上的
isProcessingOccured
设置为
true
。如果后端为我们对对象进行的
triggerProcessing
调用返回成功,那么我们将
isProcessingSuccessful
设置为
true
。例如,假设id=1和id=2的处理成功。数组必须如下所示:

    processingArray = [{id:1, isProcessingOccured: true, isProcessingSuccessful: true},
                       {id:2, isProcessingOccured: true, isProcessingSuccessful: true},
                       {id: 3, isProcessingOccured: false, isProcessingSuccessful:false }
                       .....
                       {id:k, isProcessingOccured: false, isProcessingSuccessful: false}]
如果对一个对象的处理失败,我们不能处理数组的其余部分。例如,如果对象
{id:3,isProcessingOccured:false,isProcessingSuccessful:false}
的处理失败,我们不能从
{id:4,isProcessingOccured:false,isProcessingSuccessful:false}
开始触发服务调用

我目前正在使用
async/await
来实现这一点。下面是我的代码

处理测试.component.ts

export class ProcessingDetails{
     id: string;
     isProcessingOccured: boolean;
     isProcessingSuccessful:boolean;
     constructor(id,isProcessingOccured,isProcessingSuccessful) {
          this.id = id;
          this.isProcessingOccured = isProcessingOccured;
          this.isProcessingSuccessful = isProcessingSuccessful;
     }
}
@Injectable()
export class AutomatedBatchService {
     constructor(@Inject('baseUrl') private baseUrl: string, private httpClient: HttpClient) {}

     public triggerProcessing(batchDetails:ProcessingDetails) {
         return this.httpClient.post(`${this.baseUrl}`,batchDetails);
     }
}
import { Component } from "@angular/core";
@Component({
     selector: 'processing-test',
     templateUrl: './processing-test.component.html',
     styleUrls:['./processing-test.component.css'],
     providers: [AutomatedBatchService]
})
export class ProcessingTestComponent {
     constructor(private automatedBatchService: AutomatedBatchService) { }
     public isSuccess:boolean = true;
     public processingArray: Array<ProcessingDetails>= [];
     async startBatchRun() {
         for( var i = 0; i < this.processingArray.length; i++ ) {
              if(this.isSuccess){
                 await this.automatedBatchService.triggerProcessing(this.processingArray[i])
                 .toPromise()
                 .then(res => {
                     this.processingArray[i].isProcessingOccured = true
                     this.processingArray[i].isProcessingSuccessful = true
                 })
                 .catch(rej => {
                     this.isSuccess = false
                     this.processingArray[i].isProcessingOccured = true
                     this.processingArray[i].isProcessingSuccessful = false
                 });

             }else {
                 break;
             }            
         }
     }
}
从“@angular/core”导入{Component};
@组成部分({
选择器:'处理测试',
templateUrl:“./processing test.component.html”,
styleUrls:['./处理测试.component.css'],
提供者:[AutomatedBatchService]
})
导出类ProcessingTestComponent{
构造函数(专用automatedBatchService:automatedBatchService){}
public issueccess:boolean=true;
公共处理阵列:阵列=[];
异步startBatchRun(){
对于(var i=0;i{
this.processingArray[i].isProcessingOccred=true
this.processingArray[i].isProcessingSuccessful=true
})
.catch(rej=>{
this.issucess=false
this.processingArray[i].isProcessingOccred=true
this.processingArray[i].isProcessingSuccessful=false
});
}否则{
打破
}            
}
}
}

这是实现这一目标的最佳方式吗?是否有任何方法可以完全避免使用
承诺
异步/等待
,并使用
可观察对象
实现相同的同步调用?

如果要使用可观察对象,下面的解决方案如何。它并不完美,但我想说的是,要求(同步HTTP调用)也不完美

处理-test.component.ts

import { Component, OnInit, OnDestroy } from "@angular/core";
import { Subscription } from 'rxjs';

@Component({
     selector: 'processing-test',
     templateUrl: './processing-test.component.html',
     styleUrls:['./processing-test.component.css'],
     providers: [AutomatedBatchService]
})
export class ProcessingTestComponent {
  public isSuccess = true;
  public processingArray: Array<ProcessingDetails>= [];
  private processSubscription: Subscription;

  constructor(private automatedBatchService: AutomatedBatchService) { }

  ngOnInit() {
    this.batchRun();
  }

  private batchRun() {
    let i = 0;
    if (i < this.processingArray.length) {
      this.processSubscription = this.automatedBatchService.triggerProcessing(this.processingArray[i]).subscribe(
        response => {
          this.processingArray[i].isProcessingOccured = true;
          this.processingArray[i].isProcessingSuccessful = true;
          i++;
          this.batchRun();
        },
        error => {
          this.isSuccess = false;
          this.processingArray[i].isProcessingOccured = true;
          this.processingArray[i].isProcessingSuccessful = false;
        }
      );
    }
  }

  ngOnDestroy() {
    if (this.processSubscription) {
      this.processSubscription.unsubscribe();
    }
  }
}
从“@angular/core”导入{Component,OnInit,OnDestroy};
从“rxjs”导入{Subscription};
@组成部分({
选择器:'处理测试',
templateUrl:“./processing test.component.html”,
styleUrls:['./处理测试.component.css'],
提供者:[AutomatedBatchService]
})
导出类ProcessingTestComponent{
public issueccess=true;
公共处理阵列:阵列=[];
私有进程订阅:订阅;
构造函数(专用automatedBatchService:automatedBatchService){}
恩戈尼尼特(){
这是一个.batchRun();
}
私有批处理运行(){
设i=0;
if(i{
this.processingArray[i].isProcessingOccured=true;
this.processingArray[i].isProcessingSuccessful=true;
i++;
这是一个.batchRun();
},
错误=>{
this.issucess=false;
this.processingArray[i].isProcessingOccured=true;
this.processingArray[i].isProcessingSuccessful=false;
}
);
}
}
恩贡德斯特罗(){
if(this.processSubscription){
this.processSubscription.unsubscripte();
}
}
}
自动批处理服务

import { Subject, Subscription } from "rxjs";

@Injectable()
export class AutomatedBatchService {
  private httpSubscription: Subscription;

  constructor(@Inject('baseUrl') private baseUrl: string, private httpClient: HttpClient) {}

  public triggerProcessing(batchDetails:ProcessingDetails) {
    const result = new Subject<number>();

    if (this.httpSubscription) {
      this.httpSubscription.unsubscribe();
    }
    this.httpClient.post(`${this.baseUrl}`, batchDetails).subscribe(
      response => { result.next(response.status); },
      error => { result.error(error.status); }
    );

    return result.asObservable();
  }

}
从“rxjs”导入{Subject,Subscription};
@可注射()
导出类AutomatedBatchService{
私有httpSubscription:订阅;
构造函数(@Inject('baseUrl')私有baseUrl:string,私有httpClient:httpClient){}
公共触发器处理(batchDetails:ProcessingDetails){
const result=新主题();
if(此.httpSubscription){
this.httpSubscription.unsubscripte();
}
this.httpClient.post(`this.baseUrl}`,batchDetails).subscribe(
response=>{result.next(response.status);},
error=>{result.error(error.status);}
);
返回结果。asObservable();
}
}

这种方法的一个优点是,由于我们对连续元素重复调用函数,因此如果需要,我们可以使用
setTimeout()
来诱导显式延迟。例如,在
batchRun()
函数中,调用将是
setTimeout(()=>{this.batchRun();},2000)

如果您想使用可观察对象,那么下面的解决方案如何。它并不完美,但我想说的是,要求(同步HTTP调用)也不完美

处理-test.component.ts

import { Component, OnInit, OnDestroy } from "@angular/core";
import { Subscription } from 'rxjs';

@Component({
     selector: 'processing-test',
     templateUrl: './processing-test.component.html',
     styleUrls:['./processing-test.component.css'],
     providers: [AutomatedBatchService]
})
export class ProcessingTestComponent {
  public isSuccess = true;
  public processingArray: Array<ProcessingDetails>= [];
  private processSubscription: Subscription;

  constructor(private automatedBatchService: AutomatedBatchService) { }

  ngOnInit() {
    this.batchRun();
  }

  private batchRun() {
    let i = 0;
    if (i < this.processingArray.length) {
      this.processSubscription = this.automatedBatchService.triggerProcessing(this.processingArray[i]).subscribe(
        response => {
          this.processingArray[i].isProcessingOccured = true;
          this.processingArray[i].isProcessingSuccessful = true;
          i++;
          this.batchRun();
        },
        error => {
          this.isSuccess = false;
          this.processingArray[i].isProcessingOccured = true;
          this.processingArray[i].isProcessingSuccessful = false;
        }
      );
    }
  }

  ngOnDestroy() {
    if (this.processSubscription) {
      this.processSubscription.unsubscribe();
    }
  }
}
从“@angular/core”导入{Component,OnInit,OnDestroy};
从“rxjs”导入{Subscription};
@组成部分({
选择器:'处理测试',
templateUrl:“./processing test.component.html”,
styleUrls:['./处理测试.component.css'],
提供者:[AutomatedBatchService]
})
导出类进程