Angular2 APP_INITIALIZER不一致

前端之家收集整理的这篇文章主要介绍了Angular2 APP_INITIALIZER不一致前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用APP_INITIALIZER,就像在 this的答案中推荐的那样,我的服务返回一个承诺,但并不总是等待它解决,我可以看到我的组件console.logging未定义,然后服务记录下载的对象.

我需要该应用程序在加载数据之前不做任何事情.

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();
    }
}
尝试以下代码
getUser(): Promise<User> {
    console.log('get user called');
    var promise = this.http.get('/auth/getuser',{headers: getHeaders()})
        .map(extractData)
        .toPromise();
    promise.then(user => {
        this.user = user;
        console.log(this.user);
    });
    return promise;
}

我面临着同样的问题,使用承诺而不是观察,对我来说是窍门.

原文链接:https://www.f2er.com/angularjs/140544.html

猜你在找的Angularjs相关文章