【发布时间】:2020-08-04 20:39:46
【问题描述】:
我正在尝试我的第一个 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;
}
但是在我的组件中,我尝试通过调用服务来获取页面开头的数据并将其分配给本地变量,它给出了未定义的
///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>
我也尝试了 Observables 但没有工作。我需要在调用 api 后绑定变量。有人可以建议我做错了什么
我已经检查过SO中的类似案例,但找不到类似的东西(我可能不理解)
【问题讨论】:
-
当你这样分配变量时,它不会等待异步请求结束,你的 GetAll() 方法应该返回一个可观察的并在你的组件中订阅它,然后分配你的局部变量当 observable 完成时