组件通过<router-outlet>进行通信

时间:2016-10-03 14:41:48

标签: angular

我有一个根组件,它有一个改变的布尔值,我想订阅那个改变的布尔值,我的<router-outlet>中有一个组件。我知道我需要使用某种类型的共享双向服务。但是,共享服务的文档对我来说并不是很有意义。 (我想我无法绕过宇航员的例子)here,任何帮助都会非常感激,这里有一些代码来展示我想要做的事情。

根组件

@Component({
   selector: 'my-app',
   template: `<nav [state]="boolshow"  (show)="changeValue($event)" ></nav> 
          <article><router-outlet></router-outlet></article>  <-----component in router here
          <footer></footer>
          <h3>toggle state: {{boolshow}}</h3>`,
   styleUrls: ['./Css/app.css'],

   })
 export class AppComponent {
   boolshow: boolean;      <-----boolean that needs to be read
  }

1 个答案:

答案 0 :(得分:23)

他们在Angular2 Docs中的确切表达方式:

  • 使用Observable创建服务

  • 在两个组件中注入相同的服务

  • 从一个组件更新数据到服务

  • 从其他组件中读取服务

  • 中的数据

实施例

服务:

@Injectable()
export class DataService {
    private dataObs$ = new Subject();

    getData() {
        return this.dataObs$;
    }

    updateData(data: boolean) {
        this.dataObs$.next(data);
    }
}

组件:

@Component({
  selector: 'my-app',
  template: `<div (click)="updateData(false)">Click t oupdate Data FALSE</div>
             <div (click)="updateData(true)">Click to update Data TRUE</div>
            <child></child>
            `
})
export class AppComponent {
    constructor(private dataService: DataService) {}

    updateData(value: boolean) {
      this.dataService.updateData(value);
    }
}


@Component({
  selector: 'child',
  template: `<div><p>data from Service HERE:</p><p style="color:red"> {{myData}}</p></div>`
})
export class ChildComponent {
    myData: boolean;

    constructor(private dataService: DataService) {}

    ngOnInit() {
      this.dataService.getData().subscribe(data => {
        this.myData = data;
      })
    }
}

确保在组件中注入相同的服务(Singleton):

@NgModule({
  imports:      [ BrowserModule, HttpModule ],
  declarations: [ AppComponent, ChildComponent ],
  providers: [ DataService ],
  bootstrap:    [ AppComponent ]
})

可以找到一个完整的工作示例HEREhttp://plnkr.co/edit/nJVC36y5TIGoXEfTkIp9?p=preview

PS:这是通过服务进行的通信在Angular2中的工作方式,如果你的组件通过路由器在路由器插座内部并不重要,它无处不在。