2016-06-14 3 views
1

私はバックエンドを単独で更新するモデルを持っていますが、Httpをインポートするときは定義されていません。私は(上記の例では、必ずしも構文正しさを心配していない)の後だかを示すために、クラスを単純化してきました角2 - クラス(モデル)へのHttpの挿入

var vehicle = new Vehicle(); 
vehicle.update(); //this then would update the back end 

import {Http, Headers} from "@angular/http"; 

     export class Vehicle { 
      engine:string 
      id:number 

      constructor(private http:Http){ 
      } 

      update() {    
      const body = JSON.stringify(engine); 
      const headers = new Headers(); 
      headers.append('Content-Type', 'application/json'); 
      return this._http.put('http://localhost/v1/vehicles/' + id, body, {headers: headers}) 
       .map(response => response.json()); 
      } 

     } 

アイデアは、その後のような何かを行うことです。

このシナリオでは、正しく転送され、エラーはありませんただし、httpは未定義です。

Vehicleインスタンスの内容を取得してVehicleListサービスに渡すことで、ng2サービスで必要なものを実現できますが、Vehicleクラス自体で正しく実行できるかどうか疑問に思っていました。

答えて

4

これは、自分でVehicleのインスタンスを作成するため、AngularはHttpクラスを解決できないためです。可能な解決方法は、constructorまたはupdate()メソッド自体にHttpを注入することです。

class Component1 { 
    constructor(private _http: Http) { } 

    [...] 

    var vehicle = new Vehicle(this._http); 
    vehicle.update(); 
} 

更新:参照

ため

import {HTTP_PROVIDERS, Http, Headers} from "@angular/http"; 
import {ReflectiveInjector} from '@angular/core'; 

export class Vehicle { 
    engine:string; 
    id:number; 

    constructor(private _http: Http){ 
    var injector = ReflectiveInjector.resolveAndCreate([HTTP_PROVIDERS]); 
    this._http = injector.get(Http); 
    } 

    update() {    
    const body = JSON.stringify(engine); 
    const headers = new Headers(); 
    headers.append('Content-Type', 'application/json'); 
    return this._http.put('http://localhost/v1/vehicles/' + id, body, {headers: headers}) 
     .map(response => response.json()); 
    } 
} 

Plunker: ただし、このようなReflectiveInjectorVehicleクラスでそれを自分で解決することができます

+0

VehicleクラスでHttpクラスのインスタンスを作成するには、Vehicleインスタンスを作成するときにHttpクラスを挿入する必要はありませんか? – Nik

+0

はい、私は道を見つけました。私は1秒後に更新します。 – rinukkusu

+0

なぜ 'Http'を挿入したくないのですか? –

関連する問題