angular7 - 从倒计时函数中触发模态
问题描述
我试图在我的 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">×</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
});
}
解决方案
我整理了一个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
这可以防止每次发出时间戳时在原始模式之上显示额外的模式。
推荐阅读
- c# - 如何设置 MyPackage.targets 文件以将所有 dll 添加到 bin/debug 或 bin/Release 文件夹中?
- java - 在 SashForm 中添加到运行时的 Composite 的自动适配
- go - 使用 golang 生成嵌套 JSON
- python - 如何在 docker compose 中构建和定义两个 python 服务器
- java - 仅当存在可选值时 Collectors.toMap
- javascript - 如何使用 jQuery 隐藏/显示父元素
- javascript - 按下按钮时 Ajax.load 不起作用
- hadoop - JMX 导出 Mapreduce 指标
- memory-management - 在 C++ 中使用时如何释放在 GetProcAddress() 中分配的资源?
- django - django 注销功能似乎没有破坏会话