我正在使用一个名为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未定义。
答案 0 :(得分:1)
$ 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});
}
希望它会有所帮助:)