【发布时间】:2018-06-24 17:19:18
【问题描述】:
我有以下问题。在我的 Angular6 服务中,我有一个 Http-Get 请求。我想将结果添加到我的商店。但是我管道中的tap-operator 永远不会被调用。
当我在 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});
}));
}
【问题讨论】:
-
你可能永远不会订阅 observable。或者调用返回错误响应。
-
你能说明你是怎么打电话给
LoadHistory()的吗?你应该在你的组件中调用this.budgetService.LoadHistory().subscribe(); -
@AmitChigadani 我更新了我的问题
-
在该代码 sn-p 中,您永远不会订阅
LoadHistory返回的 observable -
甚至不要在第二次更新中开始像你的方法那样做,那只会让事情变得更糟
标签: angular typescript rxjs angular6