I'm new to typescript and Angular 2.
I'd like to pass the api data in getApiData
Method to the class property currentViewData
.
However I'm getting that error:
ERROR Error: Uncaught (in promise): TypeError: Cannot set property 'currentViewData' of undefined TypeError: Cannot set property 'currentViewData' of undefined
This is my API service code:
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);
})
}
}