【问题标题】:http is not defined in angular2http未在angular2中定义
【发布时间】:2016-04-24 14:55:21
【问题描述】:

我正在尝试对我的其他本地主机服务器进行 REST Api 调用,我已提供此服务:

import {Injectable} from 'angular2/core';
import {Http} from 'angular2/http';
import {GlobalService} from '../app.service';

@Injectable()
export class AuthenticationService {
    constructor(private _globals: GlobalService) {}
    constructor(private _http: Http) {}
    globals = this._globals.getGlobals()

    getAuthenticationData() {
        this._http.get(globals.apiURL)
    }
}

并在我的组件中调用它:

import { Component } from 'angular2/core';
import {AuthenticationService} from '../services/authentication.service';

@Component({
    selector: 'wd-header';
    templateUrl: 'app/templates/header.html'
    providers: [AuthenticationService]
})

export class HeaderComponent {
    constructor(private _authenticationService: AuthenticationService) {}
    authentication = this._authenticationService.getAuthenticationData()
}

尽管出于某种原因,Angular 声称 Http 是未定义的:

异常:在 HeaderComponent 实例化期间出错!。 angular2.dev.js:22911:9

原始异常:TypeError:this._http 未定义

我做错了什么?

编辑以包含 main.ts:

import {bootstrap}    from 'angular2/platform/browser';

import {ROUTER_PROVIDERS} from 'angular2/router';
import {HTTP_PROVIDERS} from 'angular2/http';
import {App} from './app.component';
import {GlobalService} from './app.service';

bootstrap(App, [
    ROUTER_PROVIDERS,
    HTTP_PROVIDERS,
    GlobalService
]);

【问题讨论】:

  • 您的index.html 中是否引用了http.dev.js 文件?

标签: typescript angular


【解决方案1】:

我会这样重构你的服务代码:

@Injectable()
export class AuthenticationService {
  constructor(private _globals: GlobalService, private _http: Http) {
    this.globals = this._globals.getGlobals();
  }

  getAuthenticationData() {
    return this._http.get(this.globals.apiURL);
  }
}

您只需要为您的服务提供一个构造函数,并将 globals 属性初始化到此构造函数中。

还要小心使用“this”关键字从类本身引用类属性。

【讨论】:

  • 这修复了错误,但是在firefox中查看网络控制台,实际上从未发出过http请求。
  • 您需要订阅 getAuthenticationData 方法返回的对象。 Observables 是惰性的。它们仅在订阅时执行;-)
  • 你能举个例子吗?
  • 类似this.getAuthenticationData().subscribe((data) => { console.log(data); });
  • 谢谢!此外,是否有可能有角度请求 json 而不是普通的 html?如果请求,我的 API 将返回 json。
【解决方案2】:

我认为您的代码中的问题是您在AuthenticationService 中使用了两个构造函数。

尝试像这样编辑它:

constructor(private _globals: GlobalService, private _http: Http) {}

并在getAuthenticationData()中添加return语句。

如果解决了请告诉我。

【讨论】:

  • 现在_globals 未定义。
  • 所以服务还没有准备好使用。尝试在 AuthenticationService 的 onOnit 方法中初始化全局变量。 HeaderComponent 中的身份验证也是如此。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-27
  • 2016-08-21
  • 2016-09-12
  • 1970-01-01
  • 2016-04-27
  • 2016-11-04
相关资源
最近更新 更多