【发布时间】:2016-11-03 10:33:44
【问题描述】:
我的 Angular 2 项目 Http 有一些问题,我已在构造函数中将其设置为参数,在构造函数中将其打印为未定义,下面是我项目中的代码:
import 'rxjs/add/operator/toPromise';
import {Http, HttpModule, RequestOptions, XHRBackend} from "@angular/http";
import { Injectable } from '@angular/core';
@Injectable()
export class GetDataService{
private dataUrl = '/data'; // URL to web API
private req;
//mode = 'observable';
public headers;
public options;
constructor(http:Http) {
//this.http = new Http(XHRBackend, RequestOptions);
console.log(http);
}
}
这是我的错误
异常:未捕获(承诺中):错误:错误 http://localhost:3000/app/invoice.component.html:160:0 由以下原因引起: 无法读取未定义的属性“获取”
Service 使用的组件
import {Component} from '@angular/core';
import {GetDataService} from "./get-data.service";
@Component({
selector: 'http',
template: `<h4>response</h4>`
})
export class GetDataComponent {
response:string;
getDataService:GetDataService;
constructor(){
this.getDataService = new GetDataService();
console.log(this.getDataService.getData());
}
}
并在主模块提供者中添加服务
当我尝试在构造函数参数中注入 GetDataService 时
constructor(getDataService:GetDataService){
this.getDataService = getDataService;
console.log(this.getDataService.getData());
}
我明白了——
错误:(SystemJS) 无法解析 GetDataComponent 的所有参数
我也尝试在构造函数中创建 Http 对象,但我再次遇到错误。
constructor() {
this.http = new Http;
console.log(this.http);
}
this is the result of above code:
Http {_backend: undefined, _defaultOptions: undefined}
谁能帮帮我。
【问题讨论】:
-
“不工作”还不清楚。预期的行为是什么?实际行为是什么?您在哪里以及如何使用
http发出 HTTP 请求? -
我尝试在该服务的 getData 方法中发送测试获取请求,但没有一个 http.method 有效,因为 http 未定义
标签: javascript angular typescript