在子组件Angular2 / TypeScript

时间:2017-01-20 15:59:25

标签: angular typescript observable

这是一个非常简单的问题,但我是Angular2的新手,虽然我可以找到好的例子和教程,但有时我还需要更多的解释。

所以我有一个有和可观察的组件,每隔一段时间这个更新的价值。我已经在这里编辑了我的代码,但这是我的问题,你会发现一个名为product

的Observable
@Component({
  selector: 'product-profile',
  templateUrl: './product-profile.component.html',
  styleUrls: ['./product-profile.component.scss']
})
export class ProductProfileComponent {
// I have ommitted so much code here....
product: Observable<Product>;

constructor(
        private store: Store<any>
    ) {

        this.product = this.store
                    .let(getProductStore)
                    .let(getProductProfile);

        this.product
            .select((product: Product) => product && product.id)
            .subscribe(productId => this.productId = productId
            });
        }

// I have omitted so much code here....
}   

现在我有一个Child组件可能不是直接的子组件,但可能嵌套在第三级或第四级组件中,类似于

@Component({
  selector: 'product-footer',
  templateUrl: './product-footer.component.html',
  styleUrls: ['./product-footer.component.scss']
})
export class ProductFooterComponent {

// this is the same Observable / property from the parent
// when there is a change in the parent I want to update the property below... 
product: Observable<Product>;

constructor(){}
}

现在我不知道该怎么办。当父级中的产品属性的值发生更改时,如何更新子组件中的product属性。我应该使用@Input()吗?我想到了这一点,但由于关系不是直接的父母&gt;孩子的关系我不确定这是怎么回事?我应该使用某种EventEmitter吗?任何建议/链接将不胜感激,我目前有点迷失,我的资源似乎不适用!

1 个答案:

答案 0 :(得分:0)

你可以将它一直传递到你的组件中,但是当你说的有很多嵌套时,我喜欢做一些不同的事情。我创建了一个新服务,我将其范围扩展到顶级组件,子组件只是注入它并访问那里的字段。

例如,我有一个“工作区”服务,它处理子组件和顶级“工作区”组件之间的通信操作。最好的部分是,因为它的范围是这个顶级组件,你不必担心你的应用程序的其余部分混淆了这项服务。

工作区服务:

import { Injectable } from '@angular/core';


@Injectable()
export class WorkspaceService {

    public observable: Observable<any>;

}

顶级组件:

@Component({
    moduleId: module.id,
    providers: [ WorkspaceService ]
})
export class TopLevelWorkspaceComponent {

    constructor(private workspaceService: WorkspaceService) {
    }

    ngOnInit() {
        this.workspaceService.observable = /*create observable*/;
    }

}

子:

@Component({
    moduleId: module.id
})
export class NestedComponentUnderWorkspace {

    constructor(private workspaceService: WorkspaceService) {
    }

    ngOnInit() {
        this.workspaceService.observable.subscribe(data => console.log(data));
    }

}