Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 Http error

Tags:

angular

I'm starting learning Angular2 by following the quickstart they provide in their page, and now I'm trying to make some Http requests. But whenever I bootstrap the component, Chrome keeps giving me this errors:

Uncaught SyntaxError: Unexpected token <         http:1
Uncaught SyntaxError: Unexpected token <         angular2-polyfills.js:138
   Evaluating http://localhost:3000/angular2/http
   Error loading http://localhost:3000/app/boot.js

This is the component:

import {Component} from 'angular2/core';
import {HTTP_PROVIDERS, Http} from 'angular2/http';

@Component({
  selector: 'users',
  providers: [HTTP_PROVIDERS],
  templateUrl: 'app/views/users.html'
})
export class UsersComponent {

  people: Object[];
  constructor(http: Http) {
    http.get('http://192.168.56.101/api/test').subscribe(res => {
      this.people = res.json();
      console.log(this.people);
    });
  }
}

And the bootstrapping:

import {bootstrap}    from 'angular2/platform/browser'
import {UsersComponent} from './components/users'

bootstrap(UsersComponent, [HTTP_PROVIDERS]);

The view is only {{people}}.

TypeScript is compiling OK. I don't even know what's failing!

like image 508
Miguel S Avatar asked Dec 25 '15 22:12

Miguel S


People also ask

How does Angular handle HTTP errors?

When the error occurs in the HTTP Request it is intercepted and invokes the catchError . Inside the catchError you can handle the error and then use throwError to throw it to the service. We then register the Interceptor in the Providers array of the root module using the injection token HTTP_INTERCEPTORS .

What is HTTP error response?

HttpErrorResponselink A response that represents an error or failure, either from a non-successful HTTP status, an error while executing the request, or some other failure which occurred during the parsing of the response.

How do you handle error globally in Angular 6?

One traditional way of handling errors in Angular is to provide an ErrorHandler class. This class can be extended to create your own global error handler. This is also a useful way to handle all errors that occur, but is mostly useful for tracking error logs.

What are the two ranges of codes in HTTP status code for error?

Redirection messages ( 300 – 399 ) Client error responses ( 400 – 499 ) Server error responses ( 500 – 599 )


2 Answers

The documentation is lacking on that part. Router and Http need to be added to the index.html. Easy mistake to make

like image 149
mgamsjager Avatar answered Sep 22 '22 15:09

mgamsjager


First, if you injected provider on bootstrap, you don't have to do it again in component.

Second, did you included http.js in your index.html?

And third, you have an error in your code. There should be this.http.get() not http.get()

like image 37
Eggy Avatar answered Sep 22 '22 15:09

Eggy