从Angular2中的子组件访问父组件数据/属性

时间:2016-02-17 13:03:02

标签: dependency-injection typescript angular

我是#34;在我的智慧结束时"并且想知道该怎么做。我快要哭了!

在使用AngularJS多年快乐之后,我正在尝试自学Angular2 - 我有一个Angular2应用程序,它具有顶级组件,如所谓的App

@Component({
    selector: 'app', // <app></app>
    providers: [...FORM_PROVIDERS],
    directives: [...ROUTER_DIRECTIVES],
    template: require('./app.html')
})

@RouteConfig([
    {path: '/', component: Home, name: 'Home'},
    {path: 'about', component: About, name: 'About'},
    {path: 'profile', component: Profile, name: 'Profile'},
    {path: 'profile/:id', component: ForeignProfile, name: 'ForeignProfile'}
])

export class App {
    userStatus: UserStatus;
    userOnlineContacts: UserContact[];

    constructor(private userData: UserData) {
        this.userStatus = new UserStatus();
    }

    ngOnInit() {
         Observable.forkJoin([
            this.userData.getUserStatus(),
            this.userData.getContacts()
         ]).subscribe( (t) => {
                this.userStatus = t[0];
                this.userOnlineContacts = t[1].onlineContacts;
         });

        // Polling thing for this.userOnlineContacts...
        this.userData.pollContacts().subscribe(
            (data) => {
                this.userOnlineContacts = data.onlineContacts;
            });
    }
}

我在index.html

中看起来像这样
<app>Loading...</app>

现在我正在使用ng-router,所以在我的app.html中,我的<router-outlet></router-outlet>标签嵌套在我的HTML中。所以我的子组件被注入到这些标签中 - 我从未将我的选择器标签放入HTML中(因此我假设我无法使用数据绑定传递数据。在<router-outlet></router-outlet>内部我访问子组件时我导航到ForeignProfile组件,子组件代码就是这样......

@Component({
    selector: 'foreign-profile',
    template: require('app/components/foreign-profile/foreign-profile.html'),
    providers: [],
    directives: [],
    pipes: []
})

export class ForeignProfile implements OnInit {

    userProfile: any;
    routeId: string;
    userPhotos: any;
    userInfo: any;

    constructor(private userData: UserData, private routeParams: RouteParams) {
        this.routeId = routeParams.get('id');
        this.userProfile = {}; // not sure why I need to put this here otherwise we have 'undefined' error
    }

    ngOnInit() {
        // Use forkJoin as we don't need order in the calls
        Observable.forkJoin([
            this.userData.getUserPhotos(this.routeId),
            this.userData.getUserInfo(this.routeId),
            this.userData.getUserBaseData(this.routeId)])
            .subscribe(t => {
                this.userPhotos = t[0];
                this.userInfo = t[1];
                this.userProfile = t[2];
                // do more stuff here

        });
    }
}

在此组件内部,我希望访问App组件的属性,例如this.userStatus&amp; this.userOnlineContacts。我不想创建一个服务来重复HTTP调用我想将父属性直接注入到子节点中。在AngularJS中我可以使用像$scope.$parent.userStatus这样的东西。现在我通过修改组件来研究将父(App)注入子(ForeignProfile):

这是ForeignProfile组件

import {App} from '../../app'

@Component({
    // blah blah...
})

export class ForeignProfile implements OnInit {

    // code removed for example, easier to read
    userStatus: any;

    constructor(private userData: UserData, private routeParams: RouteParams, @Inject app:App) {
        // code removed for example, easier to read
        this.userStatus = app.userStatus;
    }

然后与父母......

import {Injectable, Component} from 'angular2/core';

@Injectable()
@Component({
    selector: 'app', // <app></app>

这让我的控制台发疯了。有人可以解释我是如何从我的ForeignProfile组件中的App组件访问属性的?到目前为止我浪费了几个小时!提前致谢。

1 个答案:

答案 0 :(得分:1)

正如@GünterZöchbauer正确提到的那样,您必须使用角度服务概念来实现组件之间共享数据。

如果您仍想访问App组件,可以在ForeignProfile构造函数中执行此操作:

constructor(@Host() @Inject(forwardRef(() => App)) app: App)
{

}