简体   繁体   中英

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?
  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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM