我在顶级组件中有一个属性,该属性使用了来自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"); }
);
}
}
现在,我有另一个Component,它是顶级Component的直接子代,并且我想在其中访问父代的属性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中访问父级的最佳方法是什么?