我需要该应用程序在加载数据之前不做任何事情.
app.module.ts
import { NgModule,APP_INITIALIZER } from '@angular/core'; import { Http,HttpModule,JsonpModule } from '@angular/http'; import { UserService } from '../services/user.service'; <...> @NgModule({ imports: [ BrowserModule,FormsModule,JsonpModule,routing ],declarations: [ AppComponent,<...> ],providers: [ <...> UserService,{provide: APP_INITIALIZER,useFactory: (userServ: UserService) => () => userServ.getUser(),deps: [UserService,Http],multi: true } ],bootstrap: [AppComponent]
user.service.ts
@Injectable() export class UserService { public user: User; constructor(private http: Http) { } getUser(): Promise<User> { console.log('get user called'); var observable= this.http.get('/auth/getuser',{ headers: getHeaders() }) .map(extractData); observable.subscribe(user => {this.user = user; console.log(this.user)}); return observable.toPromise(); } }