[英]Angular2 Http Providers on ES5 (not TypeScript)
我正在開發一個應用程序,並且正在玩Angular2。 我正在使用ES5 JavaScript,現在我的問題是如何訪問Http服務? 所有可用的文檔都是TypeScript(無濟於事),或者它是針對Angular2的Alpha版本的,此后系統已更改。
我正在使用Angular2版本2.0.0-beta.13。 我收到以下錯誤: TypeError: ng.http.get is not a function in [null]
。 我嘗試使用ng.http.Http.get
無濟於事。 我的頭中包含angular2-all.umd.js
,以及angular.io定義的其他js要求(RxJS,es6墊片,polyfill等)。
這是我的代碼片段,以供參考。 所有文件都串聯在一起以便於閱讀。
;(function (app, ng) { app.CommandService = (function () { var CommandService = function () { this.url = 'api/commands'; }; CommandService.prototype.all = function () { return ng.http.get(this.url) .map(function (response) { return response.json().data; }) .catch(); }; return CommandService; })(); })(window.app || (window.app = {}), window.ng); ;(function (app, ng) { app.CommandComponent = (function () { function CommandComponent(commandService) { this.commandService = commandService; this.commands = []; } CommandComponent.parameters = [ app.CommandService ]; CommandComponent.annotations = [ new ng.core.Component({ selector: '#command-listing', templateUrl: 'api/templates/commands/listing', providers: [ app.CommandService, ng.http.HTTP_PROVIDERS ] }) ]; CommandComponent.prototype.all = function () { var self = this; this.commandService.all().subscribe( function (commands) { self.commands = commands; }, function (error) { self.error = error; } ); }; CommandComponent.prototype.ngOnInit = function () { this.all(); }; return CommandComponent; })(); })(window.app || (window.app = {}), window.ng); ;(function (app, ng) { document.addEventListener('DOMContentLoaded', function () { ng.platform.browser.bootstrap(app.CommandComponent); }); })(window.app || (window.app = {}), window.ng);
從時間角度來看,TypeScript似乎不是一個可行的選擇。 我嘗試根據需要設置環境,在調試了TS問題一整天之后,我現在遇到了SystemJS問題,因此我希望普通的JS選項暫時可以滿足需要,直到我有時間弄清楚所有的復雜之處為止。
讓我知道是否需要更多信息; 我很高興給它。
更改您的CommandService
:
;(function (app, ng) {
app.CommandService = (function () {
var CommandService = function (http) { // this line changed
this.url = 'api/commands';
this.http = http; // this line added
};
CommandService.parameters = [ // this line added
ng.http.Http // this will be passed as arg in the constructor
]; // this line added
CommandService.prototype.all = function () {
return this.http.get(this.url) // this line changed
.map(function (response) {
return response.json().data;
})
.catch();
};
return CommandService;
})();
})(window.app || (window.app = {}), window.ng);
請參閱插件: http ://plnkr.co/edit/4FG1Lrt7Yhnzo20azV8Z?p=preview
作為附加信息,您可以從CommandComponent
( app/main.js
第41行)中刪除, ng.http.HTTP_PROVIDERS
在bootstrap()
處添加ng.http.HTTP_PROVIDERS
,如下所示:
document.addEventListener('DOMContentLoaded', function () {
ng.platform.browser.bootstrap(app.CommandComponent, [ng.http.HTTP_PROVIDERS]);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.