Angular 7:更新服务变量时更新组件变量

时间:2019-02-19 15:16:07

标签: angular angular-services angular-components

使用AngularJS一段时间后,我的新项目要求我使用Angular 7,因此我开始使用它。我遇到的一个问题是在两个不相关的组件之间共享数据并相应地更新它们的HTML。为此,我建立了以下服务:

import { FilterSet } from './../model/filterset.model';
import { TimeData } from './../model/timedata.model';
import { FetchDataService } from './fetchQualityData.service';
import { ConfigService } from './config.service';
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';

@Injectable()
export class SidebarService {
  public qualityData;
  public configData;
  public filterSet: FilterSet;
  public filterColor;
  public filterModel;
  public timePeriodSelected;
  public timeData: TimeData;

  constructor(
    private _configService: ConfigService,
    private _qDataSerivce: FetchDataService
  ) {
    this.timeData = {
      chosenTimeAxis: 0,
      chosenTimePeriod: 2,
      chosenDataSet: 0,
      timePeriodEnd: '2017-03-27'
    };
    this.qualityData = null;
    this.filterSet = null;
    this.filterColor = null;
    this.filterModel = null;
    this.getConfig();
  }

  getFilterSet() {
    return this.filterSet;
  }
  getQualityData() {
    return this.qualityData;
  }
  getTimeData() {
    return this.timeData;
  }
  getFilterModel() {
    return this.filterModel;
  }
  getFilterColor() {
    return this.filterColor;
  }

  setFilterSet(data) {
    this.filterSet = data;
  }
  setQualityData(data) {
    this.qualityData = data;
  }
  setTimeData(data) {
    this.timeData = data;
  }
  setFilterModel(data) {
    this.filterModel = data;
  }
  setFilterColor(data) {
    this.filterColor = data;
  }

  getQData(endDate) {
    const startDate = this._qDataSerivce.calculateStartDate(
      this.timeData.chosenTimePeriod,
      this.timeData.timePeriodEnd
    );
    this._qDataSerivce
      .fetchData(
        this.configData.dataURL,
        this.configData.user,
        startDate,
        endDate
      )
      .subscribe((response: any) => {
        this.setQualityData(
          this._qDataSerivce.dataProcessingManageObjects(response)
        );
        this.setFilterSet(this._qDataSerivce.getFilters(this.getQualityData()));
      });
  }

  getConfig() {
    this._configService.fetchConfig().subscribe((data: any) => {
      this.configData = data;
      this.getQData(this.timeData.timePeriodEnd);
    });
  }

  receiveDataSet(data) {
    this.timeData.chosenDataSet = data;
  }

  receiveFilterSet(data) {
    console.log(this.filterColor);
    this.filterColor = this.filterSet.colors[data.color];
    this.filterModel = this.filterSet.models[data.model];

    if (data.color === 0) {
      this.filterColor = null;
    }
    if (data.model === 0) {
      this.filterModel = null;
    }
  }

  receiveTimeAxis(data) {
    this.timeData.chosenTimeAxis = data;
  }

  receiveTimePeriod(data) {
    this.timeData.chosenTimePeriod = data;
    const startDate = this._qDataSerivce.calculateStartDate(
      this.timeData.chosenTimePeriod,
      this.timeData.timePeriodEnd
    );
    this._qDataSerivce
      .fetchData(
        this.configData.dataURL,
        this.configData.user,
        startDate,
        this.timeData.timePeriodEnd
      )
      .subscribe((response: any) => {
        this.setQualityData(
          this._qDataSerivce.dataProcessingManageObjects(response)
        );
        this.setFilterSet(this._qDataSerivce.getFilters(this.getQualityData()));
      });
  }

  receiveTimePeriodEnd(endDate) {
    this.timeData.timePeriodEnd = endDate;
    this.getQData(endDate);
  }
}

我试图通过此服务实现的是,当我在侧边栏中更改某些内容时,应更新使用该服务中的数据的其他组件(它们由get获取),以反映侧边栏中的更​​改。现在,当我从服务器接收到新数据后,边栏元素或其他组件元素都没有更新,它们内部的数据始终保持为空,就像初始化服务时一样。不管我是否将例如 this.filterSet 设置为新数据,这些组件都不会更新。

这是我的侧边栏组件代码

@Component({
  selector: 'app-sidebar',
  templateUrl: './sidebar.component.html',
  styleUrls: ['./sidebar.component.scss']
})
export class SidebarComponent implements OnInit, OnChanges {
  dataSetEvent;
  filterEvent;
  timeAxisEvent;
  timePeriodEvent;
  timePeriodEndEvent;
  filterSet: FilterSet;
  endOfTimePeriod = '2017-03-27';
  dataSets: Filter[];
  colors: Filter[];
  models: Filter[];
  timeAxis: Filter[];
  timePeriods: Filter[];
  colorSelected: Number;
  modelSelected: Number;
  dataSetSelected: Number;
  timeAxisSelected: Number;
  timePeriodSelected: Number;
  xAxisSwitchNotAvailable: Boolean;

  constructor(private sidebarService: SidebarService) {}

  ngOnInit() {
    // this.sidebarService
    //   .getFilterSet()
    //   .subscribe(filterSet => (this.filterSet = filterSet));
    this.filterSet = this.sidebarService.getFilterSet();
    this.xAxisSwitchNotAvailable = false;

    this.timePeriods = [
      // {
      // id: 0,
      // name: "Day"
      // },
      {
        id: 1,
        name: 'Week'
      },
      {
        id: 2,
        name: 'Month'
      },
      {
        id: 3,
        name: 'Year'
      }
    ];
    this.timePeriodSelected = 2;

    this.dataSets = [
      {
        id: 0,
        name: 'Quality Trend (Touch)'
      },
      {
        id: 1,
        name: 'Quality Trend (No-Touch)'
      }
    ];
    this.dataSetSelected = 0;

    this.timeAxis = [
      {
        id: 0,
        name: 'Date'
      },
      {
        id: 1,
        name: 'Weekdays'
      }
    ];
    this.timeAxisSelected = 0;
  }

  ngOnChanges() {
    if (this.filterSet != null) {
      this.colors = [];
      for (let i = 0; i < this.filterSet.colors.length; i++) {
        this.colors.push({
          id: i,
          name: this.filterSet.colors[i]
        });
      }

      this.models = [];
      for (let i = 0; i < this.filterSet.models.length; i++) {
        this.models.push({
          id: i,
          name: this.filterSet.models[i]
        });
      }
    } else {
      this.colors = [
        {
          id: 0,
          name: 'none'
        }
      ];
      this.colorSelected = 0;

      this.models = [
        {
          id: 0,
          name: 'none'
        }
      ];
      this.modelSelected = 0;
    }
  }

  onDataChange() {
    this.sidebarService.receiveDataSet(this.dataSetSelected);
  }

  onFilterChange() {
    const filterSetNo = {
      model: this.modelSelected,
      color: this.colorSelected
    };
    this.sidebarService.receiveFilterSet(filterSetNo);
  }

  onTimeAxisChange() {
    this.sidebarService.receiveTimeAxis(this.timeAxisSelected);
  }

  onTimePeriodChange() {
    if (this.timePeriodSelected === 3) {
      this.xAxisSwitchNotAvailable = true;
      this.timeAxisSelected = 0;
      this.sidebarService.receiveTimeAxis(this.timeAxisSelected);
    } else {
      this.xAxisSwitchNotAvailable = false;
    }
    this.sidebarService.receiveTimePeriod(this.timePeriodSelected);
  }

  updatePeriod() {
    this.sidebarService.receiveTimePeriodEnd(this.endOfTimePeriod);
  }

如您所见,我通过使用服务中的get函数获得了 this.filterSet ,它是一个对象。但是,在获得初始值之后,无论是否在服务中进行更改,它在边栏组件中均保持不变。

我尝试使用可观察性和重现(data),并订阅了该方法,但是我没有成功。我检查了是否接收到数据,以及是否在服务中使用新数据设置了this.filterSet(是我不使用set函数并直接将新数据分配给它的时候)。

我在做什么错了?

1 个答案:

答案 0 :(得分:0)

为我确认您如何注入服务。如果您没有将该服务列为模块中的提供程序(而只是将其注入到组件构造函数中),那么您将有2个单独的服务实例。

要将单例实例注入组件,该服务必须位于模块级别的提供程序数组中。