Angular 2 and TypeScript Promises

后端 未结 5 1478
孤独总比滥情好
孤独总比滥情好 2021-02-03 22:45

I\'m trying to use the routerCanDeactivate function for a component in my app. The simple way to use it is as follows:

routerCanDeactivate() {
             


        
5条回答
  •  盖世英雄少女心
    2021-02-03 23:25

    Here is a technique that worked for me. It is pretty similar to @iliacholy's answer, but uses a modal component instead of a jQuery modal. This makes it a somewhat more "Angular 2" approach. I believe it's still relevant to your question.

    First, build an Angular Component for the modal:

    import {Component, Output, EventEmitter} from '@angular/core;
    @Component({
        selector: 'myModal',
        template: `
    ` }) export class MyModal{ private hideModal: boolean = true; @Output() buttonResultEmitter = new EventEmitter(); constructor(){} openModal(){ this.hideModal = false; } closeModal(){ this.hideModal = true; } clickedYes(){ this.buttonResultEmitter.emit(true); } clickedNo(){ this.buttonResultEmitter.emit(false); } }

    Then on your component with RouterCanDeactivate(), import and reference the MyModal instance:

    import {MyModal} from './myModal';
    @Component({
        ....
        directives: [MyModal]
    })
    

    and in the class code:

    private myModal: MyModal;
    

    Create a method returning a promise, which is subscribed to the eventEmitter on myModal:

    userClick(): Promise {
        var prom: new Promise((resolve, reject) => {
            this.myModal.buttonResultEmitter.subscribe(
                (result) => {
                    if (result == true){
                        resolve(true);
                    } else {
                        reject(false);
                    }
             });
         });
         return prom;
    }
    

    and finally, in the RouterCanDeactivate hook:

    routerCanDeactivate(next: ComponentInstruction, prev: ComponentInstruction) {
        this.myModal.openModal();
        return this.userClick().catch( function(){return false;} );
    }
    

    As @drewmoore mentioned, using Observables is preferred in Angular 2, but A) that wasn't your question, and B) The routerCanDeactivate hook resolves to boolean | Promise, so this approach seemed more natural to me.

提交回复
热议问题