2016-04-23 85 views
4

我试图做一个REST API调用来我的其他本地主机服务器定义的,我做了这个服务:HTTP没有以angular2

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

出于某种原因,虽然,HTTP是不确定的角度主张:

EXCEPTION: Error during instantiation of HeaderComponent!. angular2.dev.js:22911:9

ORIGINAL EXCEPTION: TypeError: this._http is undefined

我在做什么错?

编辑包括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 
]); 
+0

@pixelbits是的。 –

+0

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

回答

2

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

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

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

你需要有一个只为您服务构造函数和全局属性初始化成此构造函数。

也要小心使用“this”关键字来引用类本身的类属性。

+0

这解决了错误,但是在firefox中查看网络控制台时,http请求实际上从来没有发生过。 –

+0

您需要订阅由getAuthenticationData方法返回的对象。观察者很懒。他们只在订阅时执行;-) –

+0

你能举个例子吗? –

2

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

尝试编辑这样说:

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

而且在getAuthenticationData()添加return语句。

让我知道它是否修复它。

+0

现在'_globals'是未定义的。 –

+0

所以这些服务还没有准备好使用。尝试在AuthenticationService的onOnit方法中初始化全局变量。在HeaderComponent中进行身份验证也是一样。 –