How to use angular2 material Dialog to block for canDeactivate

canDeactivate method can also return a Promise or Observable. You should return that and resolve the promise or emit a value on the observable with the result that you want.

In your specific example you can return the observable from the afterClosed method instead of subscribing to it, and just map it to a boolean:

return dialogRef.afterClosed().map(result => {
                if (result=='cancel'){
                    return false;
                } 
                if (result=='save'){
                    return true;
                } 
                if (result=='discard'){
                    return true;
                } 
            }).first();

Also I would move out this logic from the guard, for example in the component and just call a method from there.


Updated version for RXJS 6+ :

return dialogRef.afterClosed().pipe(map(result => {
    if (result === 'cancel') {
        return false;
    }
    if (result === 'save') {
        return true;
    }
    if (result === 'discard') {
        return true;
    }
}), first());

see https://github.com/ReactiveX/rxjs/blob/master/docs_app/content/guide/v6/migration.md

Here in particular : https://github.com/ReactiveX/rxjs/blob/master/docs_app/content/guide/v6/migration.md#howto-convert-to-pipe-syntax