在过去的4年里,我正在尝试教自己Angular2和TypeScript.无论如何,我有一个顶级组件的属性是来自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 } }
现在在Angular1.x这将很容易,因为我可以在我的子控制器中引用$parent或(ANTI PATTERN ALERT !!!)我可以非常愚蠢地将这些数据放在我的$rootScope中.在Angular2中访问父母的最佳方法是什么?提前致谢.
有不同的方式:
>全球服务
>另见
> https://github.com/escardin/angular2-community-faq/blob/master/services.md#how-do-i-communicate-between-components-using-a-shared-service
> Global Events in Angular 2
> Plunker
>父母分享的服务并注入孩子
>类似全球服务,但在提供者或viewProviders中列出,而不是boostrap(…),仅适用于父级的子级.
>父母注入孩子,并由孩子直接访问
缺点:紧耦合
export class Profile implements OnInit { constructor(@Host() parent: App) { parent.userStatus ... }
>数据绑定
export class Profile implements OnInit { @Input() userStatus:UserStatus; ... } <profile [userStatus]="userStatus">