rxjs 6管道无法在Angular 6中运行

时间:2018-06-24 17:19:19

标签: angular typescript rxjs angular6

我有以下问题。在我的Angular6服务中,我有一个Http-Get请求。我想将结果添加到我的商店。但是我管道中的tap运算符从未被调用。

当我在chrome上调试时,我看到我的http请求已执行,但该管道从未调用过我该怎么做。

import { Injectable } from '@angular/core';
import { Budget, BudgetHistory } from '../../class/budget';
import { HttpClient } from '@angular/common/http';
import { PlatformLocation } from '@angular/common';
import { HistoryOfBudget } from '../../class/budget';
import { Observable } from 'rxjs';
import {ADD,LOAD,Store} from '../../class/store';
import { map, take, merge, switchMap, switchAll, tap, debounceTime } from 'rxjs/operators'

//Get access to localStorage
export const BudgetKey : string = "budget";

@Injectable({
  providedIn: 'root'
})
export class BudgetserviceService {

  private baseUrl : string;
  private http : HttpClient;
  private budgetStore : Store<Budget> = new Store<Budget>();
  private historyStore : Store<HistoryOfBudget> = new Store<HistoryOfBudget>();
  public buget$ : Observable<Budget>;
  public history$ : Observable<HistoryOfBudget>;

  constructor(platformLocation : PlatformLocation, http : HttpClient) {
    this.baseUrl = (platformLocation as any).location.origin;
    this.http = http;
    this.buget$ = this.budgetStore.items$;
    this.history$ = this.historyStore.items$;
   }


  public LoadHistory() : Observable<HistoryOfBudget>{
    return this.http.get<HistoryOfBudget>(this.baseUrl + '/api/history').pipe(
      tap((loadedHistory) => {
      let his = new HistoryOfBudget();
      his.budget = loadedHistory.budget;
      his.historyList = loadedHistory.historyList;
      this.historyStore.dispatch({type: LOAD, data: his});
    }));
  }

}

所以这行

let his = new HistoryOfBudget();

在Chrome调试器中永远不会被击中。

我怎么了?

更新

这就是我称之为的地方。

 export class UebersichtComponent implements OnInit {

  private bs : BudgetserviceService;
  public history$: Observable<HistoryOfBudget>;

  constructor(bs : BudgetserviceService) { 
    this.bs = bs;
    this.history$ = this.bs.history$;
    this.bs.LoadHistory();
  }

  ngOnInit() {
  }

}

这是我订阅《 Observable》的地方

<div *ngIf="(history$ | async) as history; else loading">
    <div *ngFor="let his of history.historyList">
      ....
    </div>
  </div>

更新2:

我也尝试

public LoadHistory(){
this.history$ = this.http.get<HistoryOfBudget>(this.baseUrl + '/api/history').pipe(
  tap((loadedHistory) => {
  let his = new HistoryOfBudget();
  his.budget = loadedHistory.budget;
  his.historyList = loadedHistory.historyList;
  this.historyStore.dispatch({type: LOAD, data: his});
}));

}

1 个答案:

答案 0 :(得分:0)

如评论中所述,您未订阅this.bs.LoadHistory()

constructor(bs : BudgetserviceService) { 
    this.bs = bs;
    this.history$ = this.bs.history$;
    this.bs.LoadHistory().subscribe(); // update this line
}