Angular 2 BehaviorSubject组件中的数据操作反映在服务中

时间:2017-08-23 09:20:47

标签: angular rxjs behaviorsubject

这是我的DataService:

 function formatDate(date) {
        var month = '' + (date.getMonth() + 1),
            day = '' + date.getDate(),
            year = "" + date.getFullYear(),
            hour = "" + date.getHours(),
            min = "" + date.getMinutes();

        if (month.length < 2) month = '0' + month;
        if (day.length < 2) day = '0' + day;
        if (hour.length < 2) hour = '0' + hour;
        if (min.length < 2) min = '0' + min;

        return year+"/" + month +"/"+ day + " " + hour + ":" + min;
    }
    var options = {
        timeZone: 'Asia/Tokyo'
    };
    var date = new Date(1502722800000);
    console.log(formatDate(date));

这是使用DataService并格式化返回数据的组件:

private resultsChanged$: BehaviorSubject<Test[]> = 
                         new BehaviorSubject<any>([]);

constructor(private http: Http) { }

public getLatestTrends(): Observable<Test[]> {
    const latestUrl = `api/tests/trends/groupname=${this.group}&name=${this.team}`;
    return this.http.get(this.baseUrl + latestUrl)
        .switchMap((res) => {
        const json = res.json();
        console.log(json);
        this.resultsChanged$.next(json as Test[]);
        return json;
    });
}

public getSubject(): Observable<Test[]> {
    return this.resultsChanged$.asObservable();
}

}

HTML

private latestTests: Test[];
private subscription: Subscription;

constructor(private testDataService: TestDataService) { }

ngOnInit() {

  this.subscription = this.testDataService.getSubject()
      .subscribe((res) => {
          if (res === undefined || res.length < 1) {
              return;
          }

          this.latestTests = this.getFormattedTests(res.reverse());
      });
}

getFormattedTests(trends) {
    let formattedTests = [];

    if (trends === undefined || trends === null) {
        return formattedTests;
    }
    formattedTests = trends.map((trend) => {

        if (this.isPassed(trend.ran, trend.passed, trend.total)) {
            trend.state = 'check_circle';
            trend.color = 'green';
        } else {
            trend.state = 'warning';
            trend.color = 'red';
        }

        const ranPercent = this.getFixedPercent(trend.ran, trend.total);
        const passPercent = this.getFixedPercent(trend.passed, trend.ran);
        const failPercent = this.getFixedPercent(trend.failed, trend.ran);

        trend.notRun = trend.total - trend.ran;
        trend.ran = `${trend.ran} (${ranPercent})`;
        trend.passed = `${trend.passed} (${passPercent})`;
        trend.failed = `${trend.failed} (${failPercent})`;

        return trend;
    });

return formattedTests;

好的,事实是,当网站加载时,数据被格式化并保存在latestTests变量中。当我在我的路线之间循环所以再次调用ngInit时,数据再次被格式化,我不明白。奇怪的是,当我在console.log(json);在DataService中,它会记录格式化数据而不是原始数据......这怎么可能?! 就好像BehaviorSubject的数据以某种方式改变了一样。我错过了什么?

如果我需要澄清,请提供帮助和评论。

1 个答案:

答案 0 :(得分:0)

注意Subject和BehaviorSubject之间的区别:

主题的行为类似于事件总线,但不保存数据。

BehaviorSubject 可以像事件总线一样,但也会在订阅时返回流中的最后一个值。

在您的服务中,您可以声明:

public mySubject = new BehaviorSubject(null);

现在您可以使用它来执行以下操作:

this.testDataService.mySubject.subscribe(
  res => console.log(res),
  error => console.log(error)
);
this.testDataService.mySubject.next('data');

这就是全部。我希望它有所帮助