相关疑难解决方法(0)

Angular2 - 如何在组件之间共享数据/更改

因此,假设您有一个具有工具栏,侧边栏和网格的界面.工具栏有一个下拉列表,当用户更改时,侧边栏和网格中的内容会发生变化.回到Angular 1,我会使用Service来获取所有动态数据.当服务中的某些内容发生变化时,使用该服务的所有组件也将更新.

在Angular 2中,看起来人们正在使用不同的方法.我希望得到您的输入,这是首选方式.

  • 静态服务
  • OnChanges
  • 输入和输出

更新 - 03/09/16

看起来最好的解决方案是Thierry Templier发布的帖子:委托:Angular2中的EventEmitter或Observable

我剩下的问题是,最佳做法是为组件之间共享的每个数据项创建新服务,还是只有一个服务具有存储所有共享数据的对象.

import {Component} from 'angular2/core';
import {NavService} from '../services/NavService';

@Component({
  selector: 'obs-comp',
  template: `obs component, item: {{item}}`
})
export class ObservingComponent {
  item: number;
  subscription: any;
  constructor(private _navService:NavService) {}
  ngOnInit() {
    this.item = this._navService.navItem();
    this.subscription = this._navService.navChange$.subscribe(
      item => this.selectedNavItem(item));
  }
  selectedNavItem(item: number) {
    this.item = item;
  }
  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

@Component({
  selector: 'my-nav',
  template:`
    <div class="nav-item" (click)="selectedNavItem(1)">nav 1 (click me)</div>
    <div class="nav-item" (click)="selectedNavItem(2)">nav 2 …
Run Code Online (Sandbox Code Playgroud)

angular

18
推荐指数
1
解决办法
3万
查看次数

标签 统计

angular ×1