Sre*_*nga 1 rxjs angular angular8
我正在尝试我的第一个 Angular 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;
}
Run Code Online (Sandbox Code Playgroud)
但是在我的组件中,我尝试通过调用服务来获取页面开头的数据并将其分配给本地变量,它给出了未定义
///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)
}
Run Code Online (Sandbox Code Playgroud)
我的 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>
Run Code Online (Sandbox Code Playgroud)
我也试过 Observables 但没有工作。我需要在调用 api 后绑定变量。有人可以建议我做错了什么
我已经检查了 SO 中的类似案例,但找不到类似的东西(我可能不理解)
http 请求是作为异步操作完成的,因此将开始请求,但getAll
异步的执行将立即到达 return 语句并返回每个allCompanys
都有的内容。
要解决这个问题,您需要更新 GetAll 以返回一个可观察的
GetAll(): Observable<Company[]> {
return this.httpClient.get<Company[]>('https://localhost:565656/api/company')
}
Run Code Online (Sandbox Code Playgroud)
在您订阅 getAll 的组件中
this.companyService.GetAll().subscribe( result=> this.Companylist = result );
Run Code Online (Sandbox Code Playgroud)
我们可以用异步管道简化上面的代码
Companylist$ : Observable<Company[]>;
ngOnInit(){
Companylist$ = this.companyService.GetAll();
}
Run Code Online (Sandbox Code Playgroud)
模板
<tr *ngFor="let company of Companylist$ | async">
...
</tr>
Run Code Online (Sandbox Code Playgroud)
异步管道订阅 observable 并返回它发出的最新值。
另一种方法是使用async/await
,所以我们需要更新GetAll
以返回一个promise,并且使用toPromise方法很容易将observable转换为promise
GetAll(): Promise<Company[]> {
return this.httpClient.get<Company[]>('https://localhost:565656/api/company')
.toPromise(); //
}
Run Code Online (Sandbox Code Playgroud)
组件
async ngOnInit() {
this.Companylist = await this.companyService.GetAll();
...
}
Run Code Online (Sandbox Code Playgroud)
在此处阅读有关它的更多信息 async/await
归档时间: |
|
查看次数: |
7973 次 |
最近记录: |