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!
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 .
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.
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.
Redirection messages ( 300 – 399 ) Client error responses ( 400 – 499 ) Server error responses ( 500 – 599 )
The documentation is lacking on that part. Router and Http need to be added to the index.html. Easy mistake to make
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With