我正在尝试使用共享服务的组件创建一个模块 . 一个组件( graphview )具有对BehaviorSubject的可观察对象的订阅 . 另一个组件( chart-type )稍后通过调用服务中的函数( chart-config )来更新BehaviorSubject . 问题是当 ChartTypeComponent 具有服务调用 .next(data) GraphviewComponent doesn 't update. I'm时,假设正在使用该服务的多个实例,并且我不确定如何解决它 .

GraphModule (他们的父模块)在声明中有 ChartTypeComponentGraphviewComponent ,在提供者中有 ChartConfigService .

chart-config.service.ts 看起来像:

@Injectable()
export class ChartConfigService {
  private _chartconfig: BehaviorSubject<any> = new BehaviorSubject<any>({});
  public chartconfig = this._chartconfig.asObservable();
  private headers = new Headers({ 'Content-Type': 'application/json', 'charset': 'UTF-8' });
  private options = new RequestOptions({ headers: this.headers });

  constructor(private http: Http) {
      http.get('/api/chartconfig/59484e3946f7f059f1e72927')
      .map(res => res.json())
      .subscribe( data => this._chartconfig.next(data) );
    }

  getChartConfig(): Observable<any> {
    return this.chartconfig;
  }

  updateChartConfig(option, params) {
    this.http.put('/api/chartconfig/59484e3946f7f059f1e72927', '{ ' + JSON.stringify(option) + ': ' + JSON.stringify(params) + ' }' , this.options)
      .map(res => res.json())
      .subscribe( data => this._chartconfig.next(data) );
  }

graphview.component.ts 导入服务和订阅 . 它不提供服务 .

@Component({
  selector: 'app-graphview',
  templateUrl: './graphview.component.html',
  styleUrls: ['./graphview.component.scss']
})

constructor(private chartconfigService: ChartConfigService) { }

  ngOnInit() {
    this.subscription = this.chartconfigService.chartconfig
      .subscribe( data => this.localChartConfig = data );
  }

chart-type.component.ts 仅导入服务,并调用chartconfigService.updateChartConfig:

@Component({
  selector: 'app-chart-type',
  templateUrl: './chart-type.component.html',
  styleUrls: ['./chart-type.component.scss']
})

chartType(param: string) {
    this.chartconfigService.updateChartConfig('type', param);
  }

我找到了相关的问题和答案:

Delegation: EventEmitter or Observable in Angular2

Angular2 Observable BehaviorSubject service not working

但我可以做错了 . 如何在调用updateChartConfig时更新 graphview.component.ts

注意:所有调用/方法/等工作,并且在调用updateChartConfig()之后 this._chartconfig.next(data).getValue() 表明正在服务中正确更新BehaviorSubject . graphview.component.ts根本没有收到新数据 .

Update:

GraphviewComponent s ngOnInit()更改为的结果

ngOnInit() {
    this.subscription = this.chartconfigService.chartconfig
      .subscribe( data => { this.localChartConfig = data; console.log('in subscription: ' + this.localChartConfig); }, e => console.log('error: ' + e), () => console.log('then: ' + this.localChartConfig) );
  }

在控制台中生成:

in subscription: [object Object]
in subscription: [object Object]

但是在OnInit之后永远不会触发(当 ChartTypeComponent 调用updateChartConfig()时) .

Update2: 很明显,root是注入服务,而不是GraphModule:
Service Tree

Service Tree 2

我仍然希望子模块提供服务,以便它包含在子模块中 .