简体   繁体   English

http未在angular2中定义

[英]http is not defined in angular2

I'm trying to make a REST Api call to my other localhost server, I've made this service: 我正在尝试对我的其他localhost服务器进行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)
    }
}

And calling it in my component: 并在我的组件中调用它:

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

For some reason though, Angular claims that Http is undefined: 出于某种原因,Angular声称Http未定义:

EXCEPTION: Error during instantiation of HeaderComponent!. EXCEPTION:HeaderComponent实例化期间出错! angular2.dev.js:22911:9 angular2.dev.js:22911:9

ORIGINAL EXCEPTION: TypeError: this._http is undefined ORIGINAL EXCEPTION:TypeError:this._http未定义

What am I doing wrong? 我究竟做错了什么?

Edit to include main.ts: 编辑以包含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
]);

I think that the problem in your code is that you use two constructors in your AuthenticationService . 我认为您的代码中的问题是您在AuthenticationService使用了两个构造函数。

Try to edit it like this: 尝试像这样编辑它:

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

And add a return statement in getAuthenticationData() . 并在getAuthenticationData()添加一个return语句。

Let me know if it fixes it. 如果它解决了,请告诉我。

I would refactor the code of your service this way: 我会这样重构你的服务代码:

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

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

You need to have only one constructor for your service and initialize the globals property into this constructor. 您只需要为服务创建一个构造函数,并将globals属性初始化为此构造函数。

Be also careful to use the "this" keyword to reference class properties from the class itself. 还要小心使用“this”关键字来引用类本身的类属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM