this.cache没有在Angular 2 HTTP调用中设置

时间:2017-09-07 19:07:38

标签: angular typescript

我正在编写以下的打字稿,似乎无法为缓存设置值:

@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;,对我来说似乎没问题。我缺少什么?

1 个答案:

答案 0 :(得分: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
 })