简体   繁体   English

使用es5将Http插入Angular2服务

[英]http into a service with Angular2 with es5

I am working with Angular2 and es5. 我正在使用Angular2和es5。 I want to use http in a service. 我想在服务中使用http。 Unfortunately I have 2 errors: - http is undefined, but ng.http.Http is defined, - I have this error for the main component: 不幸的是,我有2个错误:-http未定义,但是ng.http.Http被定义,-主要组件出现此错误:

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

Here is my service code: 这是我的服务代码:

;(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);

Here is the main component: 这是主要组成部分:

;(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);

The bootstrap: 引导程序:

;(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);

If I try to inject http into the main component within the providers array, it works. 如果我尝试将http注入providers数组内的主要组件中,它将起作用。 But I would rather prefer to have a service. 但是我更愿意提供服务。

I found out the problem. 我发现了问题。 Looks like Angular2 needs to load your code in order. 看起来Angular2需要按顺序加载代码。 The main component was loaded before the service, so it was undefined. 主要组件在服务之前已加载,因此未定义。 I put all my code in one file and it works. 我将所有代码都放在一个文件中,并且可以正常工作。 I will use a require loader asap. 我将尽快使用require loader。

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

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