我正在试用我的第一个角锥8 Crud应用程序,并写了一个页面来列出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是called.Can之后绑定变量,有人建议我做错了什么
我已经查过了类似的情况,也找不到类似的东西(可能对我不理解)
发布于 2019-12-04 08:34:31
为您理解最简单的代码
在组件ts中:
ngOnInit() {
// callback gets executed when your service gets the response in the API call
const callback = function(companyList: Company[]) {
this.Companylist = companyList;
}
this.companyService.GetAll(callback);
console.log("At Component " + this.Companylist)
}在您的服务中:
GetAll(callback?: Function) {
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);
if(callback) {
callback(this.allCompanys);
}
}, error => console.error(error));
}发布于 2019-12-04 08:40:01
问题在于,在异步调用this.allCompanys得到解决之前,您将返回this.httpClient.get<Company[]>('https://localhost:565656/api/company')。
您可以返回一个可观察的Company[],比如返回this.httpClient.get('https://localhost:565656/api/company'),然后像allCompanys | async一样在视图中捕获它,或者您可以从方法中删除返回Company[]类型,并将其替换为空,删除返回,让this.allCompanys = result类似于订阅,这样就可以像if (this.allCompanys) { // Do something }一样控制它的值(解析时)。
发布于 2019-12-04 08:29:07
在服务中,甚至在得到响应之前就同步地返回this.allCompanys。所以它返回Undefined。但是当响应出现时,组件将不再检查更新。
因此,您需要异步更新该值。
GetAll(): Company[] {
return this.httpClient.get<Company[]>('https://localhost:565656/api/company');
}在组件中
this.companyService.GetAll().subScribe((res) => {
this.Companylist = res;
}, error => console.error(error)
)https://stackoverflow.com/questions/59171532
复制相似问题