[英]http is not defined in angular2
我正在尝试对我的其他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)
}
}
并在我的组件中调用它:
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未定义:
EXCEPTION:HeaderComponent实例化期间出错! angular2.dev.js:22911:9
ORIGINAL EXCEPTION: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
]);
我认为您的代码中的问题是您在AuthenticationService
使用了两个构造函数。
尝试像这样编辑它:
constructor(private _globals: GlobalService, private _http: Http) {}
并在getAuthenticationData()
添加一个return语句。
如果它解决了,请告诉我。
我会这样重构你的服务代码:
@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”关键字来引用类本身的类属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.