在角度8中等待服务Api调用完成 [英] Wait for Service Api call to complete in Angular 8
本文介绍了在角度8中等待服务Api调用完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试我的第一个角度8 Crud Web应用程序,并编写了一个页面来列出WebApi上的一些公司名称
我的服务正在正确获取数据,并且我能够在控制台上打印数据
//Service.ts
export class CompanyService {
allCompanys: Company[]
constructor(private httpClient: HttpClient) { }
// Returns all the companys
GetAll(): Company[] {
this.httpClient.get<Company[]>('https://localhost:565656/api/company').subscribe(result => {
this.allCompanys = result;
//Shows data Sucessfully from Server :Working fine
console.log(this.allCompanys);
}, error => console.error(error));
return this.allCompanys;
}
但在我的组件中,我试图通过调用服务来获取页面开始时的数据,并将其分配给它给出的未定义变量
///Component.ts
export class CompanyListComponent implements OnInit {
Companylist: Company[]
constructor(private route: ActivatedRoute, private router: Router, private companyService: CompanyService) { }
ngOnInit() {
this.Companylist = this.companyService.GetAll();
//This is executing before the service call is returning and returning Undefined
console.log("At Component " + this.Companylist)
}
我的html如下所示,表格未显示
//html
<tr *ngFor="let company of Companylist">
<td>{{company.Name}}</td>
<td>{{company.Phone}}</td>
<td>{{company.Email}}</td>
<td>{{company.Address}}</td>
< /tr>
我也尝试了观察项,但不起作用。我需要在调用API后绑定变量。有人能告诉我我做错了什么吗
我已经在SO中查看了类似的案例,但找不到类似的(可能是我不理解)
推荐答案
Http请求作为异步操作完成,因此将开始请求,但是执行getAll
异步将立即转到Return语句并返回每个allCompanys
所具有的内容。
要解决此问题,您需要更新getall以返回可观察的
GetAll(): Observable<Company[]> {
return this.httpClient.get<Company[]>('https://localhost:565656/api/company')
}
在您订阅的组件中
this.companyService.GetAll().subscribe( result=> this.Companylist = result );
我们可以使用异步管道来简化上述代码
Companylist$ : Observable<Company[]>;
ngOnInit(){
Companylist$ = this.companyService.GetAll();
}
模板
<tr *ngFor="let company of Companylist$ | async">
...
</tr>
异步管道订阅可观察对象并返回其发出的最新值。
🌟另一种方法是使用async/await
,因此我们需要更新GetAll
以返回承诺,并且使用将可观察到的承诺转换为Promise方法非常容易
GetAll(): Promise<Company[]> {
return this.httpClient.get<Company[]>('https://localhost:565656/api/company')
.toPromise(); // 👈
}
组件
async ngOnInit() {
this.Companylist = await this.companyService.GetAll();
...
}
点击此处了解更多信息👉async/await
这篇关于在角度8中等待服务Api调用完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文