简体   繁体   English

Angular BehavioralSubject无法正常工作

[英]Angular BehavioralSubject not working as expected

I have a service which pulls in data from the API 我有一项从API提取数据的服务

import { IStats } from './istats';
export class WebService {
  BASE_URL = 'http://localhost:3000/api';
  public stats = new BehaviorSubject<IStats>({
    date: this.datePipe.transform(new Date(), 'dd-MM-yyyy'),
    answeringMachine:0,
    hangUp:0,
    conversations:0
  });

  constructor(private http: HttpClient, private datePipe: DatePipe) {
    this.getStatsbyDate('04-03-2018');
    // this.getStatsbyDate(this.datePipe.transform(new Date(), 'dd-MM-yyyy'));
  }
  getStatsbyDate(date) {
    this.http.get<IStats>(this.BASE_URL + '/stats/' + date)
      .subscribe((data: IStats) => {
        this.stats.next(data);
      });
  }

And then I have a component which subscribes to that BehavioralSubject in the service. 然后,我有一个组件可以订阅服务中的BehavioralSubject。

export class StatsComponent {
  private stats: IStats;
  constructor(private webService: WebService, private datePipe: DatePipe)     {
    this.stats = this.webService.stats.getValue();
  }

I thought if the backend API doesn't have any data then the behavioralSubject returns the default values, which works as of now, but what if the backend does have data coming through then isn't it supposed to replace the default values with the values from the API? 我以为如果后端API没有任何数据,那么behavioralSubject返回默认值,该值从现在开始起作用,但是如果后端确实有数据通​​过,那应该用默认值替换默认值吗?从API? Is there anything wrong that I am doing here? 我在这里做错什么吗? Please advise! 请指教!

I was able to work it out making some changes on the component code 我能够解决组件代码上的一些更改

export class StatsComponent {
  private stats: IStats;
  constructor(private webService: WebService, private datePipe: DatePipe) {
    this.webService.stats$.subscribe(data => {
      if (data !== null) { this.stats = data; }  
      else { this.webService.stats$.next(this.stats); }
    })
  }

In this way the BehavioralSubject supplies the default values from the service if there is no data from API and also vice versa. 这样,如果API没有数据,那么BehavioralSubject将提供服务的默认值,反之亦然。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM