-1

I am using a framework called angular-webpack-seed, it contains, webpack, ES2016, I want to make a simple ajax call using angular like the old way but it doesn't work.

export default class HomeController {
  constructor($http) {
    'ngInject';
    this.currentPlatform = '';
    this.platforms = ["WEB PORTAL", "ROKU", "Android", "iPhone"];
  }

  makeAjaxCall() {
    // Simple GET request example:
    $http({
      method: 'GET',
      url: '/index.html'
    }).then(function successCallback(response) {
      // this callback will be called asynchronously
      // when the response is available
    }, function errorCallback(response) {
      // called asynchronously if an error occurs
      // or server returns response with an error status.
    });
  }

  setPlatform(platform) {
    this.currentPlatform = platform;
    this.makeAjaxCall();
  }

  isSelected(platform) {
    return this.currentPlatform == platform;
  }
}

Please tell me what should I configure to get the $http work, now the console prompts that $http is not defined.

2
  • $http.get('/url').then(response => { console.log(response.data) }) something like this? of course you can wrap it into function and return it from function Commented Jan 27, 2016 at 19:58
  • @The surely that wouldn't fix the "$http is not defined" error. Commented Jan 27, 2016 at 20:14

1 Answer 1

1

$http is not defined because it is only visible into the constructor.

You have to affect it to 'this' to make it available for all method into the class like this :

  constructor($http) {
    'ngInject';
    this.currentPlatform = '';
    this.platforms = ["WEB PORTAL", "ROKU", "Android", "iPhone"];
    this.$http = $http;
  }

  makeAjaxCall() {
    // Simple GET request example:
    this.$http({
      method: 'GET',
      url: '/index.html'
    }).then(function successCallback(response) {
      // this callback will be called asynchronously
      // when the response is available
    }, function errorCallback(response) {
      // called asynchronously if an error occurs
      // or server returns response with an error status.
    });
  }

On my project, I prefer use Object.assign, it is a shorter way to do it.

constructor($http, $location, $sce) {
    // affect all parameters to this
    Object.assign(this, {$http, $location, $sce}); 
}

Hope it will help :)

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much!, may I ask how to write angular directive, etc, <custom-define></custom-define>, in this webpack framewor? Or you can let me know where to find such info. Thank you again!
You can go here stackoverflow.com/questions/28620479/…. But, if you can, I suggest you to go to Angular 1.5 and use component instead of directive : simplier to write and prepare a migration to Angular2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.