2017-06-10 189 views
0

我是新來的打字稿及角2打字稿:不能訪問類屬性

我想在getApiData方法通過API數據類屬性currentViewData

但是我得到這個錯誤:

ERROR Error: Uncaught (in promise): TypeError: Cannot set property 'currentViewData' of undefined TypeError: Cannot set property 'currentViewData' of undefined

這是我的API服務代碼:

import { Injectable } from '@angular/core'; 
import { Http } from '@angular/http'; 

import 'rxjs/add/operator/toPromise'; 

@Injectable() 
export class ResourceService { 

    private baseUrl: string = 'http://api.com/blabla'; 
    private currentViewData: object; 

    constructor(private http: Http) { 

    } 

    prepareSubPath(subPath: string): string { 
     if (subPath.substr(0, 1) !== '/') { 
     return '/' + subPath; 
     } 
    } 

    getApiData(subPath: string = ''): void { 
     let url = this.baseUrl + this.prepareSubPath(subPath); 

     console.log(url); 

     let data = this.http.get(url) 
     .toPromise(); 

     data.then(function (resp) { 
     this.currentViewData = resp.json(); 
     console.info(this.currentViewData); 
     }) 
    } 
} 

回答

2

替換此代碼塊:

data.then((resp) => { 
    this.currentViewData = resp.json(); 
    console.info(this.currentViewData); 
}); 

並請閱讀文檔關於Fat Arrow Function

+0

那導致錯誤,謝謝! – btx