Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 APP_INITIALIZER not consistent

I am using APP_INITIALIZER like it is recommended in this answer, with my service returning a promise, but it doesn't always wait for it to resolve and I can see my component console.logging undefined and then the service logging the downloaded object.

I need the app to not do anything before this data is loaded.

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,
    HttpModule,
    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();
    }
}
like image 358
LLL Avatar asked Sep 27 '16 13:09

LLL


2 Answers

Try the following code:

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;
}

I was facing the same problem, and using a promise instead of a observable did the trick for me.

like image 64
Remidy Avatar answered Sep 24 '22 11:09

Remidy


I think the problem is caused because you subscribe to the observable. This should work

@Injectable()
export class UserService {

    public user: User;
    constructor(private http: Http) { }

    getUser(): Promise<User> {
        console.log('get user called');
        return observable= this.http.get('/auth/getuser', { headers: getHeaders() })
            .map(extractData)
            .do(user => {
                this.user = user;
                console.log(this.user)
             })
            .toPromise();
    }
}

I'm not sure if toPromise() is necessary. I'd expect it to work with Observable as well.

like image 41
Günter Zöchbauer Avatar answered Sep 23 '22 11:09

Günter Zöchbauer