1

I'm new to angular etc, and I have been playing around with resolve. However, when I want to pass a local boolean I get undefined? i'm trying to understand why. This below is my guard, my service just calls an api and it is passing. I want to pass a boolean to the component that the resolve is attached to, in order to display an error or not.

resolve(): boolean {
    let passed: boolean;
    let uid: string = window['appdata'].uid;
    let tbt: string = window['appdata'].tbt
    let lang: string = window['appdata'].apiUserLanguage;

    if(uid != null || undefined && tbt != null && undefined){
        console.log('Uid is: ' + uid + ' tbt is: ' + tbt);
        this.validateEmailService.emailCheck(uid, tbt, lang).subscribe( 
            data => {
                passed = true;
            },
            err => {
                passed = false;
            }
        );
    }
    console.log('Passed is: ' + passed);
    return passed;
}

}

Taranjit Kang
  • 2,510
  • 3
  • 20
  • 40
  • Something to point out from your condition: undefined is falsy. So in your condition: uid != null || undefined && tbt != null && undefined this part never gets evaluated: (undefined && tbt != null && undefined). That should be part of your issue. – Juan Jun 05 '17 at 21:47
  • You're setting the value for passed asynchronously, but you're logging the value synchronously. In other words, `console.log('Passed is: ' + passed);` happens before `this.validateEmailService.emailCheck` is completed. – Baruch Jun 05 '17 at 21:49
  • Thank you Baruch, For my particular use case i wonder if it would be better to use a promise instead of an observable and then use .then() – Taranjit Kang Jun 05 '17 at 22:05
  • Duplicate of https://stackoverflow.com/questions/6847697/how-to-return-value-from-an-asynchronous-callback-function. –  Jun 06 '17 at 01:21

1 Answers1

2

the boolean will be returned ,but you can show it after subscribing the observable returned by the service, because subscribe is an asynchrounous method. try to log it into subscribe like this & its value will be shown :)

resolve(): boolean {
let passed: boolean;
let uid: string = window['appdata'].uid;
let tbt: string = window['appdata'].tbt
let lang: string = window['appdata'].apiUserLanguage;

if(uid != null || undefined && tbt != null && undefined){
    console.log('Uid is: ' + uid + ' tbt is: ' + tbt);
    this.validateEmailService.emailCheck(uid, tbt, lang).subscribe( 
        data => {
            passed = true;
            console.log('Passed is: ' + passed);// Passed is: true
        },
        err => {
            passed = false;
            console.log('Passed is: ' + passed);// Passed is: false
        }
    );
}

return passed;

}

Mohamed Ali RACHID
  • 3,245
  • 11
  • 22