如何使用 Angular 与 ES6 和 Babel JS 进行 Ajax 调用
How to make Ajax Call using Angular with ES6 and Babel JS
>我正在使用一个名为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});
}
希望对:)有所帮助
相关文章:
- 使用agility.js进行页面布局和合成
- 如何在一个html页面上使用js进行2次乘法运算
- 将服务器js文件替换为本地js进行调试
- 使用SVG和JS进行转换
- 如何使用selenium和同步JS进行屏幕截图
- 可以'使用inter.js进行测试时不要滚动
- 使用 D3.js 进行分页
- 在使用 JS 进行选择时在文本框中显示数据
- 使用html 5和js进行拍照
- 使用Phantom.js进行无头Browserify JavaScript测试
- 使用Select2和Meteor.js进行动态数据采集
- 使用PHP和JS进行简单计算
- 可访问的更改菜单项,用于使用不引人注目的JS进行导航,而不是jQuery,
- 如何通过ssl、https Node.js进行连接
- 使用Mocha.js进行Javascript测试:如何模拟Mocha中的回调
- Magic Line在使用键盘上下移动时未使用fullPage.js进行更新
- req.user在使用express服务器passport.js进行twitter身份验证后未定义
- 使用less.js进行NETWORK_ERR
- 如何使用js进行自动平滑滚动
- MeteorJS:使用Backbone.js进行路由