路由到新页面后,服务不保留数据-Angular 8

时间:2019-07-09 16:47:04

标签: angular typescript angular-cli

我有一个Angular 8应用程序,当路由到不同页面时,我已经创建了一个DataService来访问组件之间的数据。由于某些原因,当我转到另一个页面时,数据不会保留。我已经研究了这个问题,并尝试了在这里找到的建议,但似乎没有任何效果。我一定想念一些小东西,因为我发誓它是正确的,或者至少是非常接近的。

这是我的数据服务:

import { Injectable, Injector } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';


@Injectable()
export class DataService {
  private _http: HttpClient;

  public stepOneValues = [];

  //Step One Values
  focusMetric = { name: "Focus Metric Selection(s)", value: null };
  focusMetricWeight = { name: "Metric Weights", value: null };
  preTimePeriod = { name: "Pre Time Selection", value: null };
  postTimePeriod = { name: "Post Time Selection", value: null };
  matchType = { name: "Match Type", value: null };
  overlappingControlStores = { name: "Overlapping Control Stores", value: null };
  excludeStoresCurrentlyTesting = { name: "Exclude Current Test Stores", value: null };
  excludeExceptionRecords = { name: "Exclude Exception Stores", value: null };

  constructor(injector: Injector) {}

  setStepOneValue(id, value) {
    let temp = this[id];
    temp.value = value;
    this[id] = temp;
  }

  getStepOneValues() {
    this.stepOneValues = [];

    this.stepOneValues.push(this.focusMetric);
    this.stepOneValues.push(this.focusMetricWeight);
    this.stepOneValues.push(this.preTimePeriod);
    this.stepOneValues.push(this.postTimePeriod);
    this.stepOneValues.push(this.matchType);
    this.stepOneValues.push(this.overlappingControlStores);
    this.stepOneValues.push(this.excludeStoresCurrentlyTesting);
    this.stepOneValues.push(this.excludeExceptionRecords);

    return this.stepOneValues;
  }
}

我在我的app.module.ts中提供了DataService。我的两个页面组件的构造函数中都具有该服务,如下所示:

constructor(public _dataService: DataService) { }

在值更改的第一页上,我运行以下功能:

preChange(evt) {
    console.log(evt);
    let dateString = evt.startDate.format('DD/MM/YYYY') + " - " + evt.endDate.format('DD/MM/YYYY');
    this._dataService.setStepOneValue("preTimePeriod", dateString);
    this._dataService.preTimePeriod.value = dateString;
  }

当我转到第二页时,我尝试像这样检索值:

this.stepOneValues = this._dataService.getStepOneValues();

这只是为我的preTimePeriod值返回null,我不知道为什么。超级沮丧,这就像3个小时的故障排除。

1 个答案:

答案 0 :(得分:0)

我终于弄清楚我做错了什么。我正在使用:

href="/review" 

代替:

routerLink="/review"

每次我进入新页面时,哪个实例化我的服务。