我在顶级组件中有一个属性,它使用来自 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
在我的子控制器中或(反模式警报!!!)我可能会很愚蠢地将这些数据放入我的$rootScope
.
在 Angular 2 中访问父级的最佳方式是什么?