问题描述
我想拥有一个可以自行更新后端的模型,但是当我导入Http时,它是未定义的.
I'd like to have a model that updates the back-end by itself but when I import Http it is undefined.
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());
}
}
然后的想法是做类似的事情:
The idea then is to do something like:
var vehicle = new Vehicle();
vehicle.update(); //this then would update the back end
我已经简化了该类以显示我想要的内容(在上面的示例中,不必担心语法正确性).
I've simplified the class to show what I'm after (not worried about the syntactical correctness necessarily in the above example).
在这种情况下,它可以正确转换并且没有错误但未定义http.
In this scenario, it transpiles correctly and there are no errors BUT http is undefined.
我可以通过获取Vehicle实例的内容,然后将其传递给VehicleList服务来实现ng2服务中想要的功能,但我想知道是否有可能在Vehicle类本身中做到这一点.
I can achieve what I want in an ng2 service by getting the contents of the vehicle instance and then passing them onto the VehicleList service but was wondering if it's possible to do it right in the Vehicle class itself.
推荐答案
这是因为您自己创建了 Vehicle
的实例,因此Angular无法解析 Http
为您上课.一种可能的解决方案是自己注入 Http
-在 constructor
或 update()
方法本身中.
This is because you create the instance of the Vehicle
yourself and therefore Angular can't resolve the Http
class for you. A possible solution would be to inject Http
yourself - in the constructor
or in the update()
method itself.
class Component1 {
constructor(private _http: Http) { }
[...]
var vehicle = new Vehicle(this._http);
vehicle.update();
}
更新:但是,您可以使用 ReflectiveInjector
在 Vehicle
类中自己解决该问题,
Update:You can however resolve it yourself in the Vehicle
class with the ReflectiveInjector
like this:
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());
}
}
这篇关于Angular 2-将Http插入类(模型)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!