繁体   English   中英

使用es5将Http插入Angular2服务

[英]http into a service with Angular2 with es5

我正在使用Angular2和es5。 我想在服务中使用http。 不幸的是,我有2个错误:-http未定义,但是ng.http.Http被定义,-主要组件出现此错误:

vendor-client.min.js:28 EXCEPTION: Can't resolve all parameters for class0: (t, ?)

这是我的服务代码:

;(function(app, ng) {
  console.log(new ng.http.Http());

  app.ApplicationsService = ng.core.Injectable().Class({
    constructor: [ng.http.Http, function(http) {
      console.log(http);
      this.applicationsEmailUrl = 'api/applications/email';
      this.http = http;
    }],

    emailExists: function(email) {
      console.log(email);
      var data = { email: email };
      return this.http.post(this.applicationsEmailUrl, data)
        .toPromise()
        .then(function(response) { response.json().data; })
        .catch(this.handleError);
    }

  });

})(window.app || (window.app = {}), window.ng);

这是主要组成部分:

;(function(app, ng) {

  app.AppComponent = ng.core
    .Component({
      selector: 'register-form',
      templateUrl: 'src/register/app.component.html'
    })
    .Class({
      constructor: [ng.core.ElementRef, app.ApplicationsService, function(ref, Applications) {
        console.log('app.component.js');
        this.programs = JSON.parse(ref.nativeElement.getAttribute('programs'));
        this.applications = Applications;
      }],
      emailExists: function(email) {
        console.log('emailExists() triggered');
        Applications.emailExists(email);
      }
    });

})(window.app || (window.app = {}), window.ng);

引导程序:

;(function(app, ng) {

  document.addEventListener('DOMContentLoaded', function() {
    ng.platformBrowserDynamic.bootstrap(app.AppComponent, [
      ng.forms.disableDeprecatedForms(),
      ng.forms.provideForms(),
      ng.http.HTTP_PROVIDERS,
      app.ApplicationsService
    ]);
  });

})(window.app || (window.app = {}), window.ng);

如果我尝试将http注入providers数组内的主要组件中,它将起作用。 但是我更愿意提供服务。

我发现了问题。 看起来Angular2需要按顺序加载代码。 主要组件在服务之前已加载,因此未定义。 我将所有代码都放在一个文件中,并且可以正常工作。 我将尽快使用require loader。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM