首页 > 解决方案 > 从倒计时函数中触发模态

问题描述

我试图在我的 jsonwebtoken 即将到期时触发引导模式。

我可以通过导航栏上的按钮来触发模态,但我无法让模态从函数中触发。

当我尝试使用 this.openRenew(renew) 触发模式时;我得到一个找不到名称更新错误,

**** navbar.html
<!-- Renew Token -->
<ng-template #renew let-modal>
    <div class="modal-header">
        <h4 class="modal-title" id="renewModal">Renew Log In</h4>
        <button type="button" class="close" aria-label="Close 
            (click)="modal.dismiss('Cross click')">
            <span aria-hidden="true">&times;</span>
         </button>
    </div>
    <div class="modal-body">
        Your Session In About To Expire.
        For Security Please Confirm Your Password To Continue.
        <form>
            <div class="form-group">
                <label for="password">Password</label>
                <input id="password" class="form-control"
                    placeholder="Password" name="password">
            </div>
        </form>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-outline-dark" 
            (click)="modal.close('Save click')">Log Back In</button>
    </div>
</ng-template>


**** navbar.ts

constructor(
    public _auth:AuthService,
    public _router:Router,
    public modalService: NgbModal) {
        this._auth.time.subscribe((now: Date) => {
            this.currentTime = now.valueOf();
            if(!!this._auth.emToken){
                if (!this.timeToRenew || this._auth.emExpTime==null){
                    console.log('Checking Time to renew', 
                        this._auth.emExpTime*1000-this.currentTime );
                    if((this._auth.emExpTime*1000)-45000<this.currentTime){
                        this.timeToRenew = true;
                        console.log('Time to Log Back In');
                         / * Need to trigger openRenew() here *
                    }
                }
            }
        });
    }

openRenew(renew) {
    this.modalService.open(renew, {ariaLabelledBy: 
         'renewModal'}).result.then(
         (result) => {
             console.log(result);
             // validate password 
    });
 }

标签: angular7ng-bootstrap

解决方案


我整理了一个StackBlitz 演示来展示它的工作原理。它应该在大约 10 秒后自动显示模态。

您需要对代码进行一些更改才能使其正常工作:

一世。确保您可以在 TS 文件中获取对模态模板的引用,方法是使用以下代码将模板声明为类变量并使用@ViewChild在 HTML 中获取对它的引用:

@ViewChild('renew')
private renew: TemplateRef<any>; 

我修改了逻辑以使演示更简单——在这个例子中,AuthService每 5 秒触发一次。组件会监听这个,如果 发出的时间戳AuthService在组件创建后大于 10 秒,它会显示模态。

ii. 您需要将订阅分配给一个变量subscription,以便您可以在打开模式时取消订阅:

// 1. Maintain a reference to the subscription
const subscription: Subscription = this._auth.time.subscribe((now: Date) => {
    ...
    if (/*should renew*/) {
        this.openRenew(this.renew);
        subscription.unsubscribe(); // 2. Unsubscribe here after opening modal
    }
});

AuthService这可以防止每次发出时间戳时在原始模式之上显示额外的模式。


推荐阅读