Shane
Shane

Reputation: 5677

Load data before component inialization - angular 2

My App.component which calls a init method in my user service.

ngOnInit(){
    this.init(true).then(data => {
        console.log("OnInit Called")
    })     
}

User.service returns a promise which in turn calls the account.init

init = (isRegistered) => {
    return new Promise((resolve, reject) => {    
        this.account.init(isRegistered).then(data => {
            //some data inialization
            console.log("OnInit Called User Service")            
        });          
    });   
}

Account.service returns a promise which calls several services using Observable.forkJoin

init = ((userType: boolean) => {
    return new Promise((resolve, reject) => {
         Observable.forkJoin([
             this.m1,
             this.m2]).subscribe(data => {
                 //persist those return data   
             });           
    });
}
  1. Why are both console.log statements never gets executed?
  2. Why does it not prevent the component inialization before the Observable.forkJoin complets its service calls?

Upvotes: 1

Views: 501

Answers (2)

martin
martin

Reputation: 96949

You definitely have to resolve the Promise first.

init = (isRegistered) => {
    return new Promise((resolve, reject) => {    
        this.account.init(isRegistered).then(data => {
            // some data initialization
            if (data) {
                resolve(...);
            } else {
                reject(...);
            }
            console.log("OnInit Called User Service")            
        });          
    });   
}

It's hard to tell what's the problem because we don't know what this.m1 and this.m2 are.

Don't get surprised when using forkJoin(). This operator forkJoin() doesn't emit any value if one of its source Observables fail or doesn't emit any value and complete prematurely.

Upvotes: 2

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657721

  1. (and 2.) call to resolve(...) missing
init = (isRegistered) => {
    return new Promise((resolve, reject) => {    
        this.account.init(isRegistered).then(data => {
            //some data inialization
            console.log("OnInit Called User Service")            
            resolve(/*someValue */); // <<<== missing
            // or reject(/* someValue */);
        });          
    });   
}
  1. Why do you expect it to block anything? ngOnInit() can't be blocked. You can for example use *ngIf to not show anything before the data is not yet available. You can also use a router guard to prevent component creation before data is available. https://angular.io/docs/ts/latest/guide/router.html#!#resolve-guard But there is no way to block execution in any way in JS.

Upvotes: 2

Related Questions