我正在尝试通过HTTP GET在一个组件中加载数据,然后我需要在动态加载的子组件中使用这些数据。
以下是代码:
ngOnInit(){
this.accountService.getPersonalInfo().subscribe(
response => {
this.Account = response.json();
this.dcl.loadIntoLocation(HeaderComponent, this.elementRef, 'header')
.then(compRef => {
compRef.instance.Account=this.Account;
}
);
}
);
}
在子组件(HeaderComponent)中,我可以使用this.Account
来获取此数据。有更好的方法吗?
答案 0 :(得分:1)
您只需提供一个祖先组件
@Component({
selector: 'header-cmp',
...
})
class HeaderCmp {
constructor(private account:AccountService) {
this.account.someObservable.subscribe(...); // or whatever
}
}
@Component({
selector: 'parent-cmp',
providers: [AccountService],
...
})
class ParentCmp {
constructor(private account:AccountService) {
// set some values
}
}
您提供"服务的组件"可以是实际执行this.dcl.loadIntoLocation(...)
的组件,也可以是链上的其他一些祖先组件。