Search code examples
httpangularecmascript-5

Get an error from Angular2 http in Es5


I am trying to use http with Angular2. Here is my code:

  var _domain = 'http://localhost:3000/';

   app.Applications = ng.core.Injectable().Class({
      constructor: [ng.http.Http, function(http) {
        this.http = http;
        this.emailExistUrl = _domain + 'api/applications/email';
      }],

      doesEmailExist: function(email) {
        var data = { email: email };
        return this.http.post(this.emailExistUrl, data)
          .toPromise()
          .then(function(response) { response.json().data; })
          .catch(this.handleError);
      }
    });

The main component:

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

Here is main.js file:

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

When doesEmailExist is called I get an error from the http module:

vendor-client.min.js:55470 TypeError: Cannot read property 'platform_browser_private' of undefined

Any ideas?

FIXED: Http was before platform-browser on the script tag list. :/

<script src="https://npmcdn.com/@angular/http/bundles/http.umd.js"></script>
<script src="https://npmcdn.com/@angular/platform-browser/bundles/platform-browser.umd.js"></script>
<script src="https://npmcdn.com/@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js"></script>

The inverse is better :)


Solution

  • Try to assign http at the beginning of the constructor:

       app.Applications = ng.core.Injectable().Class({
          constructor: [ng.http.Http, function(http) {
            this.http = http;
            ...
          }],
    
          doesEmailExist: function(email) {
            ...
          }
        });
    

    EDIT See this Plunker: http://plnkr.co/edit/aQWqxauklT7MqSjfhLFD. To simplify, I have put everything in main.js file, and instead of an http post I have implemented an http get. However, locally, even the http post works with a web service API. I hope it's helpful to solve your problem.