2017-09-07 23 views
0

我寫了下面的打字稿似乎並不能設定爲高速緩存的值:this.cache沒有棱角2 HTTP設置內調用

@Injectable() 
export class FundsService { 

    private cache : Observable<Fund[]>; 

    // Fetch all existing comments 
    getFunds(useCache : boolean = true) : Observable<Fund[]> { 

     // add authorization header with jwt token 
     let headers = new Headers({ 
      'Authorization': 'Bearer ' + this.authenticationService.token 
     }); 
     let options = new RequestOptions({ headers: headers }); 

     // if cache set, return 
     console.log(this.cache) 
     if (useCache && this.cache) { 
      console.log("using cache") 
      return this.cache; 
     } 

     return this.http.get(this.fundsUrl, options) 
      .map((res:Response) => { 

       // store in cache 
       console.log("setting cache") 
       this.cache = res.json(); 
       console.log(this.cache) 

       // return json 
       return res.json() 

      }) 
      .catch((error:any) => Observable.throw(error.json().error || 'Server error')); 
    } 
} 

是「本」錯了嗎?當我在TypeScript Playground中檢查編譯的JS時,我可以看到var _this = this;,對我來說似乎還可以。我錯過了什麼?

+0

所以你看'的console.log( 「設置高速緩存」)'在控制檯? – spottedmahn

+0

,你確定'useCache'是'true'? – spottedmahn

回答

0

嘗試更換

.map((res:Response) => { 

// store in cache 
console.log("setting cache") 
this.cache = res.json(); 
console.log(this.cache) 

// return json 
return res.json() 
} 

通過

.map((res:Response) => res.json()) 
.forEach(json => { 
    this.cache = json 
})