【发布时间】:2016-01-20 21:22:41
【问题描述】:
我正在使用 angular2,但在将 Http 注入另一个服务时遇到了问题。
这是我的boot.ts 文件:
import { bootstrap } from 'angular2/platform/browser';
import { provide } from 'angular2/core';
import { AppComponent } from './app.component';
import { appInjector } from './app-injector';
import { LoginService } from './services/login.service';
import { HTTP_PROVIDERS, Http } from 'angular2/http';
import { RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS,
LocationStrategy, HashLocationStrategy} from 'angular2/router';
bootstrap(AppComponent,
[ROUTER_PROVIDERS, LoginService, provide(
LocationStrategy, {useClass: HashLocationStrategy}
)]
).then((appRef) => {
// store a reference to the injector
appInjector(appRef.injector);
});
这是我的app.component.ts 文件:
import {Component} from 'angular2/core';
import {RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS,
LocationStrategy, HashLocationStrategy} from 'angular2/router';
import {LoginService} from './services/login.service';
import {HTTP_PROVIDERS, Http} from 'angular2/http';
@Component({
selector: 'my-app',
templateUrl: 'app/templates/app.tpl.html',
directives: [ROUTER_DIRECTIVES],
providers: [LoginService, HTTP_PROVIDERS]
})
export class AppComponent {
constructor(private _loginService: LoginService) { }
login() {
this._loginService.login();
}
}
这是有问题的login.service.ts 文件:
import {Injectable} from 'angular2/core';
import {Http,Headers} from 'angular2/http';
@Injectable()
export class LoginService{
http: Http;
constructor(_http: Http) {
this.http = _http;
}
login(){
// do sth
}
}
问题在于login.service.ts 文件中的constructor。
当我删除构造函数中的参数(留下constructor(){})时,页面呈现正常。当我保留Http 参数时,页面不会呈现,而是在浏览器控制台中我看到:Uncaught SyntaxError: Unexpected token < 错误。
我需要将Http 注入我的LoginService,但我找不到问题所在。我查看了一些博客和 SO 问题,即here,但没有运气。
【问题讨论】:
标签: service dependency-injection angular