[英]Angular9 Modals using Promise
I am trying to make a modal in Angular 9 that returns a Promise as result.我正在尝试在 Angular 9 中创建一个模式,结果返回 Promise。 I don't know how to move the promise logic outside of the declaration.
我不知道如何将 promise 逻辑移到声明之外。
<a class="button-primary" (click)="yes()">Yes</a>
<a class="button-default" (click)="no()">No</a>
This is the modal controller这是模态 controller
import { Component, OnInit, HostBinding } from '@angular/core';
@Component({
selector: 'change-username-modal',
templateUrl: './change-username-modal.component.html',
styleUrls: ['./change-username-modal.component.less']
})
export class ChangeUsernameModalComponent implements OnInit {
@HostBinding('class.show')
show: boolean = false;
constructor() { }
ngOnInit(): void {
console.log('init');
}
public open(): Promise<boolean> {
return new Promise(function(resolve, reject) {
resolve(true);
});
}
yes() {
//this.myPromise.resolve(true);
this.show = false;
}
no() {
//this.myPromise.reject(false);
this.show = false;
}
}
I need to make the Promise resolve or reject when calling the yes() or no() functions.在调用 yes() 或 no() 函数时,我需要使 Promise 解析或拒绝。 Thank you in advance!
先感谢您!
You could use Observable approach instead of promise.您可以使用 Observable 方法代替 promise。 you need a simple subject which will emit and complete immediately (for avoiding memory leak).
您需要一个简单的主题,它将立即发出并完成(以避免 memory 泄漏)。 the code should look like this
代码应该是这样的
export class Component{
@HostBinding('class.show')
show: boolean = false;
private _emitter$ = new Subject<boolean>();
constructor() { }
ngOnInit(): void {
console.log('init');
}
public open(): Observable<boolean> {
return this._emitter.asObservable();
}
yes() {
//this.myPromise.resolve(true);
this.show = false;
this.emitAndClose(true);
}
emitAndClose(answer:boolean){
this._emitter.next(answer);
this._emitter.complete();
}
no() {
this.emitAndClose(false);
this.show = false;
}
}
now whenever answer is clicked, it will emit the value and complete the subject so you don't need unsubscribe outside现在,每当单击答案时,它都会发出值并完成主题,因此您不需要在外面取消订阅
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.