1

I have a problem with accessing data from Service in Controller. Here`s my Service's file code:

import {IHttpService} from 'Angular';

export class MyService {
public static $inject = ['$http'];
constructor(private $http:IHttpService, private getItems){

this.getItems= function() {
  this.$http.get('items.json').then(function(response){
    if(err){
      console.error(err);
    }
    console.log(response.data);
    return response.data;
  });
}}}

And Controller`s file code:

import {MyService} from './MyService';
export class MyController {
public:getData;
static inject: Array<string> = ['$http', '$scope', 'MyService'];
constructor(private $http:ng.IHttpService, private $scope:any, private MyService:any){
    this.getData = function(){
      MyService.getItems.then(function (data) {
      this.getItems = data;

      console.log(data);
    });
  }

}

Can anybody explain me what`s wrong with my code? Thanks.

2 Answers 2

0

Return the promise inside the getItems method, It should be,

this.getItems= function() {
  return this.$http.get('items.json').then(function(response){
    if(err){
      console.error(err);
    }
    console.log(response.data);
    return response.data;
  });
}}}
Sign up to request clarification or add additional context in comments.

Comments

0

Change function declaration to either in below way or use Arrow function so that the this(context) of class would be preserve. Also you must return $http promise from getItems method, otherwise you can not apply .then method over it to chain promise.

getItems() {
  //return promise here.
  return this.$http.get('items.json').then((response) => {
    if(err){
      console.error(err);
    }
    console.log(response.data);
    //returning data to chained promise.
    return response.data;
  });
}

1 Comment

Downvoter would you mind to say, why you downvoted? Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.