创建子模块为所有组件提供单一服务

时间:2017-06-20 23:56:44

标签: angular rxjs angular-services behaviorsubject angular-observable

我试图制作一个包含共享服务的组件的模块。一个组件( graphview )订阅了一个BehaviorSubject的可观察对象。另一个组件(图表类型)稍后通过调用服务中的函数( chart-config )来更新BehaviorSubject。问题是当ChartTypeComponent有服务电话.next(data) GraphviewComponent没有更新时。我假设正在使用多个服务实例,而且我不确定如何修复它。

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根本就没有收到新数据。

更新

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

我仍然喜欢提供服务的子模块,以便它包含在子模块中。

0 个答案:

没有答案
相关问题