首页 文章

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

提问于
浏览
2

我“在我的智慧结束时”并且不知道该怎么做 . 我快要哭了!

在使用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.userStatusthis.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 回答

  • 1

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

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

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

相关问题