我正在使用angular,当我的每个元素完成每个元素的发布请求后,我需要发出一个新事件。
这些元素是用户,对于每个元素,我都需要发出发布请求以将其注册到我的服务器上。
这是我的代码:
export class CustomerBulkImport {
@Output() customersAdded = new EventEmitter<boolean>();
...
...
registerCustomers(){
let usersRegistered = this.records.forEach( customer=>{
customer.owner = this.owner
this.service.register(this.strategy,customer).subscribe((res:NbAuthResult)=>{
this.submitted = true;
if (res.isSuccess()) {
this.messages = res.getMessages();
this.tokenStorage.set(this.currentToken)
} else {
this.errors = res.getErrors();
}
this.cd.detectChanges();
})
});
this.customersAdded.emit(true)
console.log('emitted')
}
}
正如您在此处看到的那样,我的console.log('emitted')正在forEach结束之前执行。
答案 0 :(得分:1)
这是由于可观察对象的异步性质。您可以使用forkjoin击打多个并行调用并订阅它们,以便您知道所有调用何时完成。
registerCustomers(){
let myCalls = this.records.map((customer) => {
customer.owner= this.owner;
return this.service.register(this.strategy, customer).pipe(map(res:NbAuthResult) => {
this.submitted = true;
if (res.isSuccess()) {
this.messages = res.getMessages();
this.tokenStorage.set(this.currentToken)
} else {
this.errors = res.getErrors();
}
this.cd.detectChanges();
}));
});
forkJoin(myCalls).subscribe(() => {
this.customersAdded.emit(true)
console.log('emitted')
});
}