如何访问escope以外的变量?
导出类ClientsComponent实现OnInit { title:string =“所有客户”
clients: Client[] = [];
response: any;
total_clients: number;
total_pages: number;
pages: any[] = [];
constructor( private _clientService: ClientService ) {}
ngOnInit() {
this._clientService.getData()
.subscribe(
data => this.response = data,
err => console.error(err),
() => {
this.clients = this.response.data,
this.total_clients = this.response.total
}
);
console.log(this.total_clients); <- i can not access this
}
答案 0 :(得分:1)
它不在范围之外,当在控制台中打印this.total_clients
时,它还没有填充。所有HTTP请求都是异步操作,因此如果您想要访问它,您可以在订阅中执行此操作,如下所示:
ngOnInit() {
this._clientService.getData()
.subscribe(
data => this.response = data,
err => console.error(err),
() => {
this.clients = this.response.data,
this.total_clients = this.response.total
console.log(this.total_clients); <- this will print your data
}
);
console.log(this.total_clients); <- this is executed before the call is finished, as you will see
}
答案 1 :(得分:0)
您需要在构造函数中初始化变量,然后在异步调用的回调中填充它。这是完整的代码:
export class ClientsComponent implements OnInit { title: string = "All Clients"
clients: Client[] = [];
response: any;
total_clients: number;
total_pages: number;
pages: any[] = [];
constructor( private _clientService: ClientService ) {
this.clients = [];
this.total_clients = 0l
}
ngOnInit() {
this._clientService.getData()
.subscribe(
data => {
this.clients = this.response.data;
this.total_clients = this.response.total;
}
err => console.error(err)
);
}
}