3

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.

2 Answers 2

3

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);
Sign up to request clarification or add additional context in comments.

4 Comments

this solves the problem, thanks, but I think also the response @PankajParkar
I have no idea what to accept, I think the two helped with the error.
I tried, as was the code unchanged, as published and your answer is the solution
Yea, dilemma, feel free to accept whatever you you want, it's fine :)
3

Seems like somehow Http isn't get injected correctly. Use @Inject to inject Http dependency.

import { Component, Inject} from 'angular2/core';
//above code should be at start.

constructor(@Inject(Http) http: Http) {

@Inject is needed for acquiring dependency when not using Typescript for transpilation of JS.

7 Comments

Maybe I doing something wrong that I add this import {Inject} from 'angular2/core'; and constructor(@Inject(Http) http: Http){ and obtain equal error
@AngelAngel may I know which angular2 version you are using?
"dependencies": { "angular2": "2.0.0-beta.3",
@AngelAngel have you added rx.js, you need to add rxjs/add/operators/map because you are using map operator
I have -> import 'rxjs/add/operator/map'; this refers to that? in this file
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.