我在顶级组件中有一个属性,它使用来自 HTTP 源的数据,如下所示(这是在一个名为 app.ts
的文件中):
import {UserData} from './services/user-data/UserData';
Component({
selector: 'app', // <app></app>
providers: [...FORM_PROVIDERS],
directives: [...ROUTER_DIRECTIVES],
pipes: [],
template: require('./app.html')
})
@RouteConfig([
// stuff here
])
export class App {
// Please note that UserData is an Injectable Service I have written
userStatus: UserStatus;
constructor(private userData: UserData) {
this.userStatus = new UserStatus();
}
ngOnInit() {
this.userData.getUserStatus()
.subscribe(
(status) => {
this.userStatus = status; // I want to access this in my Child Components...
},
(err) => {console.log(err);},
() => {console.log("User status complete"); }
);
}
}
现在,我有另一个组件,它是顶级组件的直接子组件,在其中我想访问父组件的属性’ userStatus
‘,这是子组件:
Component({
selector: 'profile',
template: require('app/components/profile/profile.html'),
providers: [],
directives: [],
pipes: []
})
export class Profile implements OnInit {
constructor() {
}
ngOnInit() {
// I want to have access with the parent App Component, 'userStatus' propety here... I only want to read this property
}
}
现在在 Angular 1.x 中这很容易,因为我可以在我的子控制器中引用 $parent
或( ANTI PATTERN ALERT!!! )我可能很愚蠢地将这些数据放入我的 $rootScope
.
在 Angular 2 中访问父级的最佳方式是什么?
原文由 Mike Sav 发布,翻译遵循 CC BY-SA 4.0 许可协议
有不同的方式:
全球服务
由父级共享并注入子级的服务
providers
或viewProviders
中列出,而不是boostrap(...)
并且仅适用于父母的孩子。父级注入子级并由子级直接访问