[英]Use injected dependency in jQuery event listener in angular
I'm using Bootstrap 4 modals in Angular 6 and I want to redirect the user to another route once the modal is closed. 我在Angular 6中使用Bootstrap 4模态,并且一旦模态关闭,我想将用户重定向到另一条路线。 However, I'm getting a scoping issue when the modal is closed telling me that my injected router is undefined.
但是,当模式关闭时,我遇到了一个范围界定问题,告诉我我注入的路由器未定义。
My code: 我的代码:
import { Component, OnInit } from '@angular/core';
declare var $: any
@Component({
selector: 'app-modal',
templateUrl: './modal.component.html',
styleUrls: ['./modal.component.css']
})
export class ModalComponent implements OnInit {
constructor(
public router: Router
) {}
ngOnInit() {}
ngAfterViewInit() {
$('#mymodal').on('hidden.bs.modal', function (e) {
router.navigate(['/']) //tells me that router is undefined
})
}
}
Use this
to have access to the router
as an injected dependency and arrow function syntax( (e) => {}
) to rescope it to the correct scope. 使用
this
可以作为注入的依赖项访问router
,并使用箭头函数语法( (e) => {}
)将其范围限定到正确的范围。 Like this: 像这样:
ngAfterViewInit() {
$('#mymodal').on('hidden.bs.modal', (e) => {
this.router.navigate(['/']);
})
}
Use this
keyword like that in Jquery
. 像在
Jquery
一样使用this
关键字。
ngAfterViewInit() {
var self = this;
$('#mymodal').on('hidden.bs.modal', function (e) {
self.router.navigate(['/']);
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.