jin*_*bat -1 typescript angular
我已经成功调用了 API 并从中调用了数据,但是如果我读取了变量,我会得到"Undefined"。
调用api获取数据的服务类
export class DataServiceService {
constructor(private http: Http) { }
url: string = "http://localhost:60263/api/values";
getEmployeesData(): Observable<EmployeeDetails[]> {
return this.http.get(this.url).map((res: Response) => res.json());
}
}
Run Code Online (Sandbox Code Playgroud)
订阅数据
export class AppComponent {
emp: EmployeeDetails[];
constructor(private dataServe: DataServiceService) { }
ngOnInit() {
this.dataServe.getEmployeesData().subscribe(res => this.emp = res);
}
clEmployeesCount: Number = this.emp.length; **Getting undefined here**
clShowEmployee: boolean = false;
clCreateEmployee: boolean = false;
}
Run Code Online (Sandbox Code Playgroud)
但是这在 HTML 部分工作正常
<div *ngIf="emp">
<ul *ngFor="let user of emp">
<li>{{user.ID}}</li>
</ul>
</div>
Run Code Online (Sandbox Code Playgroud)
由于它是一个异步调用,您无法知道它何时会被返回。所以将赋值移到subscribe
函数中
this.dataServe.getEmployeesData().subscribe(res => {
this.emp = res;
this.clEmployeesCount = emp.length;
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
9708 次 |
最近记录: |