【问题标题】:Http not working in Angular 2Http 在 Angular 2 中不起作用
【发布时间】: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


【解决方案1】:

Http 不应使用new Http() 创建。

HttpModule 添加到您的@NgModule({ imports: [BrowserModule, HttpModule], ...}) 并使用第一个示例中所示的构造函数注入Http

更多详情见https://angular.io/docs/ts/latest/tutorial/toh-pt6.html

【讨论】:

  • 当我尝试在参数中注入 http 时,我收到错误 http undefined - "Cannot read property 'get' of undefined"
  • 您是否将HttpModule 添加到imports,如我的回答所示?
  • GetDataService 是如何以及在何处注入的?
  • 请编辑您的问题并在此处添加代码。 cmets 中的代码不可读。
  • 导致此错误的代码未包含在您的问题“无法读取未定义的属性'get'”中
猜你喜欢
  • 2018-01-25
  • 1970-01-01
  • 2017-11-17
  • 2017-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-18
  • 1970-01-01
相关资源
最近更新 更多