2017-01-04 59 views
0

我嘗試訪問緩存數據在我管,但總是出現以下錯誤:不能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 
+1

您無法訂閱不存在的對象。首先實例化對象,然後嘗試「訂閱」(即錯誤消息的含義) – zerohero

回答

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方法。

+0

謝謝!我也添加share()...任何想法爲什麼請求觸發2次?我希望只有一個請求。我用日誌更新第一篇文章。 – robert

+1

observable將按照訂閱的頻率執行。我也希望它只用'share()'執行一次。 –