如何使用 Angular 与 ES6 和 Babel JS 进行 Ajax 调用

How to make Ajax Call using Angular with ES6 and Babel JS

本文关键字:JS 进行 Ajax 调用 Babel 何使用 Angular ES6      更新时间:2023-09-26

>我正在使用一个名为angular-webpack-seed的框架,它包含webpack,ES2016,我想像旧方式一样使用angular进行一个简单的ajax调用,但它不起作用。

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;
  }
}

请告诉我应该配置什么才能使$http正常工作,现在控制台提示未定义$http。

未定义$http,因为它仅在构造函数中可见。

您必须将其影响为"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.
    });
  }

在我的项目中,我更喜欢使用Object.assign,这是一种较短的方法。

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

希望对:)有所帮助