Angular 2如何手动解决承诺?

时间:2016-06-30 14:57:02

标签: javascript typescript angular promise

如何在指令中解决Angular 2中的承诺?我正在尝试做一个简单的图像加载指令:

@Directive({
    selector: '[carouselImage]',
    host: {
        '(load)' : 'onImageLoad()'
    }
})
class CarouselImageDirective {
    private _promise: Promise;
    private _loaded: boolean = false;

    constructor(private _elRef: ElementRef, private _renderer: Renderer) {

    }

    loadImage() {
        this._promise = new Promise<ElementRef>( resolve => {
            resolve(this._elRef);
        });

    }

    onImageLoad() {
        this._promise.resolve(); //this won't work
        this._loaded = true;
        console.log('Image loaded ', this._elRef);
    }
}

到目前为止,我的尝试无效。

1 个答案:

答案 0 :(得分:1)

你可以尝试类似的东西:

loadImage() {
    this._promise = new Promise<ElementRef>( resolve => {
        this.resolve = resolve;
    });

}

onImageLoad() {
    this.resolve(this._elRef);
    this._loaded = true;
    console.log('Image loaded ', this._elRef);
}