Angular 如何从服务功能到组件获取数据?
目前我正在学习。大多数事情都不起作用。为了了解更多,我有一个问题。在我的组件中,我从调用json的函数中得到了一个返回。 这是我的代码:Angular 如何从服务功能到组件获取数据?,angular,observable,Angular,Observable,目前我正在学习。大多数事情都不起作用。为了了解更多,我有一个问题。在我的组件中,我从调用json的函数中得到了一个返回。 这是我的代码: total Items: number = 3; //<-- data.total_items needed here ngOnInit() { return this.customerdataService.getCustomersList().subscribe(data => { console.log(data) });
total Items: number = 3; //<-- data.total_items needed here
ngOnInit() {
return this.customerdataService.getCustomersList().subscribe(data => {
console.log(data)
});
}
项目总数:数量=3;//{
console.log(数据)
});
}
到目前为止,数据显示在我的组件输出中。但对于分页,我需要CustomerComponent类中的数据。这里我必须定义totalItems、currentPage等。我尝试了不同的方法,但没有任何结果,比如:data.current\u页面
我必须在构造函数中使用它吗?您的代码没有什么意义,
ngOnInit
不会返回任何内容,也不会有任何帮助,因为您也无法处理订阅
可观察对象发出数据,该数据将在subscribe
的数据回调期间可用
this.customerdataService.getCustomersList().subscribe(
data => {
console.log(data);
this.total_Items = data.total_items; // assignment
});
如何做得更好?这是从youtube教程中获得的。@SaschaK您可以将此代码放入您的
ngOnInit()
中。这是将从可观察对象返回的数据分配到组件中所需位置的正确方法。非常感谢您的帮助。如果我的函数中不存在此代码“我得到”属性?请根据项目调整名称,它们可能会有不同的名称。在这种情况下,最好的方法是使用一个包含所有分页内容信息的BaseComponent
,并在使用分页的位置使用BaseComponent扩展所有组件。所有分页内容都可以在组件中使用,而不是在每个组件中单独定义。