Angular 2和TypeScript的承诺 [英] Angular 2 and TypeScript Promises

查看:91
本文介绍了Angular 2和TypeScript的承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对我的应用程序中的组件使用routerCanDeactivate函数.使用它的简单方法如下:

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

routerCanDeactivate() {
    return confirm('Are you sure you want to leave this screen?');
}

我唯一的问题是它很丑.它只是使用浏览器生成的确认提示.我真的很想使用自定义模式,例如Bootstrap模式.我让Bootstrap模态根据他们单击的按钮返回一个真值或假值.我正在实现的routerCanDeactivate可以接受true/false值,也可以接受解析为true/false的promise.

My only issue with this is that it's ugly. It just uses a browser generated confirm prompt. I really want to use a custom modal, like a Bootstrap modal. I have the Bootstrap modal returning a true or false value based on the button they click. The routerCanDeactivate I'm implementing can accept a true/false value or a promise that resolves to true/false.

这是具有routerCanDeactivate方法的组件的代码:

Here is the code for the component that has the routerCanDeactivate method:

export class MyComponent implements CanDeactivate {
    private promise: Promise<boolean>;

    routerCanDeactivate() {
        $('#modal').modal('show');
        return this.promise;
    }

    handleRespone(res: boolean) {
        if(res) {
            this.promise.resolve(res);
        } else {
            this.promise.reject(res);
        }
    }
}

编译我的TypeScript文件时,在终端中出现以下错误:

When my TypeScript files compile, I get the following errors in the terminal:

error TS2339: Property 'resolve' does not exist on type 'Promise<boolean>'.
error TS2339: Property 'reject' does not exist on type 'Promise<boolean>'.

当我尝试离开组件时,模态启动,但是随后组件停用,并且不等待承诺解决.

When I try to leave the component, the modal starts, but then the component deactivates and doesn't wait for the promise to resolve.

我的问题是尝试计算Promise,以便routerCanDeactivate方法等待应许解决.为什么有错误说明Promise<boolean>上没有'resolve'属性的原因?如果我可以解决这一问题,必须在routerCanDeactivate方法中返回什么,以便它等待对诺言的解决/拒绝?

My issue is trying to work out the Promise so that the routerCanDeactivate method waits for the promise to resolve. Is there a reason why there is an error saying that there is no 'resolve' property on Promise<boolean>? If I can work that part out, what must I return in the routerCanDeactivate method so that it waits for the resolution/rejection of the promise?

作为参考,这是DefinitelyTyped Promise定义 .显然那里有解决和拒绝的功能.

For reference, here is the DefinitelyTyped Promise definition. There is clearly a resolve and reject function on there.

感谢您的帮助.

更新

这是更新的文件,其中Promise已初始化:

Here is the updated file, with the Promise being initialized:

private promise: Promise<boolean> = new Promise(
    ( resolve: (res: boolean)=> void, reject: (res: boolean)=> void) => {
        const res: boolean = false;
        resolve(res);
    }
);

handleResponse函数:

handleResponse(res: boolean) {
    console.log('res: ', res);
    this.promise.then(res => {
        console.log('res: ', res);
    });
}

它仍然无法正常工作,但是模态显示并等待响应.如果您说是请假,它将停留在组件上.另外,记录的第一个res是从组件返回的正确值,但是.then函数内部的那个与传递给handleResponse函数的那个​​不同.

It still doesn't work correctly, but the modal shows up and waits for the response. When you say yes leave, it stays on the component. Also, the first res that is logged is the correct value returned from the component, but the one inside .then function is not the same as the one passed in to the handleResponse function.

更多更新

More Updates

经过更多阅读后,看来在promise声明中,它设置了resolve值,而promise则具有该值,无论如何.因此,即使以后我调用.then方法,它也不会更改promise的值,并且我也无法实现它并切换组件.有没有办法使promise没有默认值,而必须等到其.then方法被调用?

After doing some more reading, it appears that in the promise declaration, it sets the resolve value, and the promise has that value no matter what. So even though later on I call the .then method, it doesn't change the value of the promise and I can't make it true and switch components. Is there a way to make the promise not have a default value and that it has to wait until the its .then method is invoked?

更新的功能:

private promise: Promise<boolean> = new Promise((resolve, reject) => resolve(false) );

handleResponse(res: any) {
    this.promise.then(val => {
        val = res;
    });
}

再次感谢您的帮助.

最新更新

Last Update

考虑了很多建议后,我决定创建一个Deferred类.效果很好,但是当我执行deferred.reject(anyType)时,控制台出现错误:

After looking at many suggestions, I decided to create a Deferred class. It's worked pretty well, but when I do the deferred.reject(anyType), I get an error in the console of:

EXCEPTION: Error: Uncaught (in promise): null

当我传入nullstringboolean时,也会发生同样的事情.尝试在Deferred类中提供catch函数无效.

This same thing happens when I pass in null, a string, or a boolean. Trying to provide a catch function in the Deferred class didn't work.

延期课程

Deferred Class

export class Deferred<T> {
    promise: Promise<T>;
    resolve: (value?: T | PromiseLike<T>) => void;
    reject:  (reason?: any) => void;

    constructor() {
        this.promise = new Promise<T>((resolve, reject) => {
            this.resolve = resolve;
            this.reject  = reject;
        });
    }
}

推荐答案

我对bootstrap模态api不熟悉,但是我希望在创建它时有某种方式可以将其绑定到close事件./p>

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<boolean> {
    let $modal = $('#modal').modal();
    return new Promise<boolean>((resolve, reject) => {
      $modal.on("hidden.bs.modal", result => {
        resolve(result.ok);
      });
      $modal.modal("show");
    });
  }

}

您正试图像Deferred一样使用Promise.如果您需要这种API,请为自己编写一个Deferred类.

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

class Deferred<T> {

  promise: Promise<T>;
  resolve: (value?: T | PromiseLike<T>) => void;
  reject:  (reason?: any) => void;

  constructor() {
    this.promise = new Promise<T>((resolve, reject) => {
      this.resolve = resolve;
      this.reject  = reject;
    });
  }
}

export class MyComponent implements CanDeactivate {

    private deferred = new Deferred<boolean>();

    routerCanDeactivate(): Promise<boolean> {
        $("#modal").modal("show");
        return this.deferred.promise;
    }

    handleRespone(res: boolean): void {
        if (res) {
            this.deferred.resolve(res);
        } else {
            this.deferred.reject(res);
        }
    }
}

这篇关于Angular 2和TypeScript的承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆