Seb*_*sen 5 typescript angular
我正在尝试对我的其他本地主机服务器进行 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)
}
}
Run Code Online (Sandbox Code Playgroud)
并在我的组件中调用它:
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()
}
Run Code Online (Sandbox Code Playgroud)
但出于某种原因,Angular 声称 Http 未定义:
异常: HeaderComponent 实例化期间出错!。angular2.dev.js:22911:9
原始异常:类型错误: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
]);
Run Code Online (Sandbox Code Playgroud)
我会这样重构你的服务代码:
@Injectable()
export class AuthenticationService {
constructor(private _globals: GlobalService, private _http: Http) {
this.globals = this._globals.getGlobals();
}
getAuthenticationData() {
return this._http.get(this.globals.apiURL);
}
}
Run Code Online (Sandbox Code Playgroud)
您的服务只需要一个构造函数,并将全局属性初始化到该构造函数中。
还要小心使用“this”关键字从类本身引用类属性。
| 归档时间: |
|
| 查看次数: |
5192 次 |
| 最近记录: |