我正在使用angular2並在將Http
注入到其他服務時遇到問題。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
}
}
的問題是與constructor
在中文件。
當我刪除構造函數中的參數(離開constructor(){}
)頁面呈現正常。當我保留Http
參數時,頁面不呈現,而是在瀏覽器控制檯中看到:Uncaught SyntaxError: Unexpected token <
錯誤。
我需要將Http
注入我的LoginService
,但我找不到問題所在。我已經看過一些博客和SO問題,即here,但沒有運氣。