2016-02-11 41 views
3

我想在嘗試幾種方法在線教程後使用下面的代碼,我不能使它工作。錯誤使用Http JSON AngularJS 2

..// 
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); 
    } 

獲得此錯誤:

EXCEPTION: Error during evaluation of "click"

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

誰能告訴我我做錯了,我爲我的英語很抱歉。

回答

3

那麼,因爲錯誤消息狀態this.http不是一個函數,它是一個有幾個方法的對象。你需要this.http.get()方法:

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

這解決了這個問題,謝謝,但我認爲也應答@PankajParkar –

+0

我不知道接受什麼,我認爲兩人幫助解決了這個錯誤。 –

+0

我試了,因爲代碼沒有改變,發佈和答案是解決方案 –

3

看起來像某種方式Http沒有得到正確注入。使用@Inject來注入Http依賴項。

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

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

@Inject對於在不使用Typescript進行JS的轉譯時獲得依賴性是必需的。

+0

也許我做錯了,我從'angular2/core'添加此導入{注入};和構造函數(@Inject(Http)http:Http){並獲得相同的錯誤 –

+0

@AngelAngel我可以知道您使用的是哪個angular2版本? –

+0

「依賴關係」:{ 「angular2」:「2.0.0-beta.3」, –