簡體   English   中英

Angular 2-將Http插入類(模型)

[英]Angular 2 - Insert Http into a class (model)

我想要一個可以自行更新后端的模型,但是當我導入Http時,它是未定義的。

    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());
          }

        }

然后的想法是做類似的事情:

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

我已經簡化了該類以顯示我要學習的內容(在上面的示例中不必擔心語法正確性)。

在這種情況下,它將正確地進行編譯,並且沒有錯誤, 但是未定義http。

我可以通過獲取vehicle實例的內容,然后將其傳遞給VehicleList服務來實現ng2服務中想要的功能,但是我想知道是否可以在Vehicle類本身中正確地實現它。

這是因為您自己創建了Vehicle的實例,因此Angular無法為您解析Http類。 一種可能的解決方案是自己注入Httpconstructor或在update()方法本身中。

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

    [...]

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

更新:但是,您可以使用ReflectiveInjectorVehicle類中自行解決,如下所示:

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());
  }
}

柱塞供參考

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM