首页 文章

Angular 2如何将变量从父组件传递到路由器出口

提问于
浏览
8

我发现的所有教程和答案都只显示了如何使用输入将变量从父组件传递给子组件,但是这个子组件包含在路由器出口中而不是直接在父模板中?

例如:

Main component

@Component({
  selector: 'my-app',
  template: `
          Main page
          <router-outlet></router-outlet>
              `,
  directives: [ROUTER_DIRECTIVES]
})

@RouteConfig([
    { path: '/contact', name: 'Contact', component: ContactComponent},
 ])

export class AppComponent{
  public num:Number = 123;
}





@Component({
   selector: 'contact-page',
   template: 'contact page'
})
export class ContactComponent{
   public num:Number;
}

因此,在此示例中,主组件模板包含一个路由器出口,其中将呈现子联系人组件,但如何在父组件组件的路由器出口内评估的子组件中获取变量“num”值?

3 回答

  • -1

    我只是偶然发现了这个问题,这就是我如何解决类似的问题 .

    我会使用服务来解决这个问题 . 然后,所有子项和父项都可以设置该属性,并为所有订阅者传播更改 . 首先,我将创建一个具有私有BehaviorSubject的服务,该服务具有公共getter和setter,以封装ReplaySubject并仅返回Observable:

    private _property$: BehaviorSubject<number> = new BehaviorSubject(1);
    
    set property(value: number) {
        this._property$.next(value);
    }
    
    get property$(): Observable<number> {
        return this._property$.asObservable();
    }
    

    使用新的BehaviorSubject(1)的原因是将初始值设置为1,因此可以订阅 .

    在父onInit中,我会选择property(num)的默认值:

    private _propertySubscribtion: Subscription
    
    ngOnInit() {
        // set default value to 5
        this._componentService.property = 5;
    
        // If property is updated outside parent
        this._componentService.property$.subscribe(p => {
            this.property = p;
        });
    }
    
    ngOnDestroy() {
        this._propertySubscribtion.unsubscribe();
    }
    

    在一个或多个子组件中,可以订阅更改:

    private _propertySubscribtion: Subscription
    
    ngOnInit() {
        this._propertySubscribtion = this._componentService.property$.subscribe(p => {
            this.property = p;
        });
    }
    
    ngOnDestroy() {
        this._propertySubscribtion.unsubscribe();
    }
    

    如果某个孩子或父母更新了该 property :

    updateProperty() {
        // update property
        this._componentService.property = 8;
    }
    

    所有订阅者都会知道它 .

  • 0

    目前,您无法绑定到路由器添加的组件 . 改为使用共享服务(此处已有大量示例),可以从添加的组件传递数据,也可以订阅事件 .

    另见此问题https://github.com/angular/angular/issues/4452特别是此评论https://github.com/angular/angular/issues/4452#issuecomment-153889558

  • 3

    如果您的数据是不可变的,则可以使用RouteData .

    @Component({...})
    @RouteConfig([
        { path: '/contact', name: 'Contact', component: ContactComponent, data: {num: 123}},
     ])
    export class AppComponent {
    }
    
    @Component({...})
    export class ContactComponent {
       public num:Number;
       constructor(data: RouteData) {
         this.num = data.get('num');
       }
    }
    

    传递一些您不想在子路由中进行硬编码的配置选项会很有用 . 但是,如果您期望数据发生变化,那么您还需要一些其他方法 .

相关问题