0

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);
      })
   }
}
R. Richards
  • 24,603
  • 10
  • 64
  • 64
btx
  • 1,972
  • 3
  • 24
  • 36

1 Answers1

3

Replace this code block :

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

And please read the doc about the Fat Arrow Function

Vivek Doshi
  • 56,649
  • 12
  • 110
  • 122