Angular 2 and TypeScript Promises

后端 未结 5 1489
孤独总比滥情好
孤独总比滥情好 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:22

    I'm not familiar with the bootstrap modal api, but I'd expect there to be a way to bind to a close event somehow when creating it.

    export class MyComponent implements CanDeactivate {
    
      routerCanDeactivate(): Promise {
        let $modal = $('#modal').modal();
        return new Promise((resolve, reject) => {
          $modal.on("hidden.bs.modal", result => {
            resolve(result.ok);
          });
          $modal.modal("show");
        });
      }
    
    }
    

    You're trying to use the Promise like Deferred. If you want that kind of API, write yourself a Deferred class.

    class Deferred {
    
      promise: Promise;
      resolve: (value?: T | PromiseLike) => void;
      reject:  (reason?: any) => void;
    
      constructor() {
        this.promise = new Promise((resolve, reject) => {
          this.resolve = resolve;
          this.reject  = reject;
        });
      }
    }
    
    export class MyComponent implements CanDeactivate {
    
        private deferred = new Deferred();
    
        routerCanDeactivate(): Promise {
            $("#modal").modal("show");
            return this.deferred.promise;
        }
    
        handleRespone(res: boolean): void {
            if (res) {
                this.deferred.resolve(res);
            } else {
                this.deferred.reject(res);
            }
        }
    }
    

提交回复
热议问题