如何使用angular 6服务更新组件数据

时间:2018-09-21 01:32:54

标签: angular observable

我有一个角度6数据服务,该服务设置了一个可观察的对象,该对象将与至少一个组件共享。

我已经尝试遵循此类功能的设计模式。

问题在于,尽管我的组件似乎接收了默认值,但它从未更新数据。

数据服务如下:

IFS

,组件外观如下:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, BehaviorSubject, Subscription, fromEvent } from 'rxjs';

@Injectable()
export class CustomerDataService {
  dataURL = 'assets/data/customer_sim_data_rollup.json';
  private customerData = new BehaviorSubject([{"product": "init1", "revenue": 1, "yearmo": 201801}, {"product": "init2", "revenue": 1, "yearmo": 201801}]);
  currentCustData = this.customerData.asObservable()
  // private currentCustData = new Observable();

  constructor(private http: HttpClient) {
    console.log('customer-data-service was called...');
    this.getData();
  }

  getData(yearmo: string): void {
    console.log('getData was called...');
    this.http.get(this.dataURL).subscribe(data => this.updateData(data)));
  }

  filterData(data: any, yearmo: string): any[]{
    return data.filter(d => d['yearmo'] === yearmo);
  }

  updateData(data: any): void{
    data = this.filterData(data, '201801')
    this.customerData.next(data);
  }
}

该组件订阅服务中的可观察对象,然后调用import { Component, OnInit, NgModule, OnChanges, SimpleChanges, Input } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { BrowserAnimationsModule} from '@angular/platform-browser/animations'; import { CustomerDataService } from '../services/customer-data.service'; import { NgxEchartsModule } from 'ngx-echarts'; @Component({ selector: 'app-treemap', templateUrl: './treemap.component.html', styleUrls: ['./treemap.component.css'] }) export class TreemapComponent implements OnInit { @Input() data: any[]; results: any[]; constructor(private custDataService: CustomerDataService) { } ngOnInit() { this.custDataService.currentCustData.subscribe(data => this.data = data; console.log(this.data);); this.custDataService.getData('201802'); } ngOnChanges(changes: SimpleChanges): void { if( changes['data'] ){ console.log('the data changed') this.results = this.parseData(this.data); } } parseData(data): any[] { let parsedData = data.forEach(d => {"name": d["products"], "value": d["revenue"]}); return parsedData; } } @NgModule({ imports:[ NgxEchartsModule, ], }) export class AppModule { } 。我希望这既可以更新服务又可以触发this.custDataService.getData('201802');,但似乎都不会发生。

控制台输出如下:

enter image description here

我做错了什么?

1 个答案:

答案 0 :(得分:1)

行为是正确的。在同一组件中更新变量时,ngOnChanges不会触发。您需要做的就是在您的订阅中调用parseData方法,它将起作用

this.custDataService.currentCustData.subscribe(data => {
  this.data = data; 
  console.log(this.data);
  this.results = this.parseData(this.data);
});

注意:当您在包含应用程序树形图组件的同时从模板传递数据时,ngOnChanges将触发

<app-treemap [data]="someData"></app-treemap> //this will trigger onChange event

在您的订阅中,您已经在获取数据,因此无需依赖更改检测