【问题标题】:How to update component data w angular 6 service如何使用 Angular 6 服务更新组件数据
【发布时间】:2018-09-21 10:31:29
【问题描述】:

我有一个 Angular 6 数据服务,它设置了一个要与至少一个组件共享的 observable。

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

问题在于,虽然我的组件似乎接收到默认值,但它从不更新数据。

数据服务如下所示:

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 { }

组件订阅服务中的observable,然后调用this.custDataService.getData('201802');。我希望这会更新服务并触发ngOnChanges,但似乎都没有发生。

控制台输出如下所示:

我做错了什么?

【问题讨论】:

    标签: angular observable


    【解决方案1】:

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

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

    注意:当您从模板传递数据同时包含 app-treemap 组件时,ngOnChanges 将触发

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-03
      • 1970-01-01
      • 2019-03-24
      • 2018-12-15
      • 1970-01-01
      • 2018-03-23
      • 2019-08-07
      • 1970-01-01
      相关资源
      最近更新 更多