Shane Shane - 4 years ago 270
TypeScript Question

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?


Answer Source
  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.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download