gpt4 book ai didi

typescript - angular2 中未定义 http

转载 作者:太空狗 更新时间:2023-10-29 17:52:49 25 4
gpt4 key购买 nike

我正在尝试对我的其他本地主机服务器进行 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: 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
]);

最佳答案

我将以这种方式重构您的服务代码:

@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”关键字从类本身引用类属性。

关于typescript - angular2 中未定义 http,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36817653/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com