Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error using Http JSON AngularJS 2

Tags:

angular

I'm trying to use the following code after trying several ways online tutorials I can not make it work.

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

@Component({

    viewProviders: [HTTP_PROVIDERS],

    template: `
    ..//
    <div class="col-md-6 col-md-offset-3 well">

        <input type="button" class="btn btn-success btn-block"
        (click)="get()" value="Fetch Users">

        <hr>
        <ul>
           <li *ngFor="#user of users">
             Id: {{ user.name }} | Name: {{ user.name }} | JSON: {{ user | json }}
           </li>
        </ul>
    </div>

    ..//

export class Mov {

    //Inicio test http

    users: Array<Object>;
    http: any;

    //
    //constructor(@Inject(HttpFactory) http) {
    //constructor(http: Http) {
    constructor(http: Http){
         //
        this.http = http;
    }

    get(){
        this.http('resources/users.json')
        .map(res => res.json())
        .subscribe(users => this.users = users);
    }

obtain this error:

EXCEPTION: Error during evaluation of "click"

ORIGINAL EXCEPTION: TypeError: this.http is not a function

anyone can tell me I'm doing wrong, I'm sorry for my English.

like image 895
Angel Angel Avatar asked Apr 20 '26 11:04

Angel Angel


1 Answers

Well, as the error message states this.http is not a function, it's an object which has several methods. You need this.http.get() method:

this.http.get('resources/users.json')
    .map(res => res.json())
    .subscribe(users => this.users = users);
like image 148
dfsq Avatar answered Apr 23 '26 10:04

dfsq



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!