我嘗試訪問緩存數據在我管,但總是出現以下錯誤:不能subscripe緩存服務
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
您無法訂閱不存在的對象。首先實例化對象,然後嘗試「訂閱」(即錯誤消息的含義) – zerohero