访问ngOnInit()-Angular 4中构造函数内部调用的Async方法的值



我是angular的新手。有一种情况,我不知道下一步该怎么办。每一个建议和解决方案都将受到欢迎。

constructor() {
this.getCustomers();
}

该.getCustomers((方法将为customers变量赋值。

async getCustomers() {
let response = await this.customerService.get();
this.customers = response.data;
}

get((返回一个带有customer数组的promise array[6]

ngOnInit() {
console.log(this.customers) // undefined
} 

这里是这个。客户是未定义的

在Angular中使用异步函数的最佳和最推荐的方法是使用Observables。让我给你看看。

首先,您有一个向应用程序后端发出HTTP请求的服务。(我想你已经熟悉这些服务了,所以让我们来解释一下它的功能(

public get() {
// This is the get method of your customer service
return this._http.get("http://your-backend/customers");
}

您应该提供Http服务来使用它,上面的方法将返回一个Observable。现在,您已经准备好捕捉组件的响应了。组件:

public customers: Customer[]; 
constructor( private customerService: CustomerService ) {
// It's not a good practice to call here to your customer service so just define the variable where you'll store the data
this.customers = [];
}
ngOnInit() {
// Now here is where you call to get the data
this.customerService.get()
.subscribe( res => {
this.customers = res;
console.log(this.customers); // Here you will have the customers
});

console.log(this.customers); // Here the array is empty
}

最新更新