我尝试访问管道中的缓存数据,但总是收到以下错误:
Cannot read property 'subscribe' of undefined
服务:
import { Injectable } from '@angular/core';
import {Observable} from 'rxjs/Rx';
import 'rxjs/observable/of';
import 'rxjs/add/operator/map';
@Injectable()
export class FormDataService {
private apiUrl = "http://localhost";
private data:any;
private observable: Observable<any>;
constructor(
private _http: Http
){}
getCountries() {
if(this.data) {
console.log("data available");
return Observable.of(this.data);
} else if(this.observable) {
console.log("request pending")
return this.observable;
} else {
console.log("request data");
this.observable = this._http.get(this.apiUrl + "/country")
.map(res => {
console.log("data received");
this.observable = null;
this.data = res.json();
});
}
}
管道:
export class ResolvePipe implements PipeTransform {
constructor(
public _formDataService: FormDataService
) {}
transform(value: number, args: any[]): any {
return this._formDataService.getCountries().subscribe(
data => {
console.log(data);
return data;
}
)
}
}
我有另一个问题:
api返回一个对象数组
[{id:1,label:"USA",id:2, label:"DE", ...}]
管道应该用标签替换id(值)...你会在哪里这样做?在服务或管道?
编辑:
formdata.service.ts:27 request data
formdata.service.ts:30 data received
formdata.service.ts:27 request data
formdata.service.ts:24 request pending (822 times)
formdata.service.ts:30 data received
答案 0 :(得分:2)
缺少回复
getCountries() {
if(this.data) {
console.log("data available");
return Observable.of(this.data);
} else if(this.observable) {
console.log("request pending")
return this.observable;
} else {
console.log("request data");
this.observable = this._http.get(this.apiUrl + "/country")
.map(res => {
console.log("data received");
this.observable = null;
this.data = res.json();
});
return this.observable; // <<<<
}
}
否则将返回null
,null
不提供subscribe
方法。