[英]Angular 8: Run Component Class Methods Synchronously/Sequentially
How do I run methods synchronously in Angular Typescript?如何在 Angular Typescript 中同步运行方法? These are not functions, but methods.这些不是函数,而是方法。 First one calls a service, and then second saves into an array.第一个调用服务,然后第二个保存到数组中。
runTwoMethods()
{
this.validateAddress();
this.saveJsonArchive();
}
Validate address may call more sub-method,may not even be Api, so want to wait until everything completes before saving.验证地址可能会调用更多的子方法,甚至可能不是Api,所以要等到一切都完成后再保存。
Following syntax is for functions, currently searching for class methods,以下语法用于函数,目前正在搜索 class 方法,
Angular / TypeScript - Call a function after another one has been completed Angular / TypeScript - 在另一个完成后调用 function
At the end, data is stored into a current data object.最后将数据存入当前数据object。 And I want to be save to an archive.我想保存到档案中。 Maybe another possibility, how do I keep AddressCurrentMailing and JSONArchive[2] in sync?也许另一种可能性,我如何保持 AddressCurrentMailing 和 JSONArchive[2] 同步?
Current Data object is sourced from API, not sure where (nor I am not allowed to edit the APIs, then calls transformations), and then would like to save into JsonArchive.当前数据 object 来自 API,不知道在哪里(我也不允许编辑 API,然后调用转换),然后想保存到 JsonArchive。
this.jsonArchive[this.jsonArchiveCounter] = this.addressCurrentMailingFinalData
You can use Observable
for the 1st and use your 2nd method after Subscribe
in callback:您可以在第一个使用Observable
并在回调中Subscribe
后使用您的第二个方法:
validateAddress(): Observable<Someclassname>
{
return this._http.get<Someclassname>('url');
}
this.yourService.validateAddress().subscribe(
(result) => {
this.saveJsonArchive();
},
(error) => console.log('NO saveJsonArchive'));
EDIT ( validateAddress
with more one Observable
)编辑( validateAddress
与多个Observable
)
const ox: Observable<Someclassname>[] = [];
ox.push(this.http.get<Someclassname>(url1));
ox.push(this.http.get<Someclassname>(url2));
ox.push(this.http.get<Someclassname>(url3));
forkJoin(ox).subscribe(result => this.saveJsonArchive());
You could return a Promise in "this.validateAddress();"您可以在“this.validateAddress();”中返回 Promise; and await it.并等待它。
I assume you use the Angular HttpClient.我假设您使用 Angular HttpClient。
For example:例如:
private validateAddress(): Promise<someclassname>
{
return this._http.get<someclassname>("someurl").toPromise()
}
async addSeasonal()
{
await this.validateAddress();
await this.saveJsonArchive();
}
I hope this helps.我希望这有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.