javascript - 在 Angular 中的 jQuery 事件监听器中使用注入(inject)的依赖项

标签 javascript angular scope

我在 Angular 6 中使用 Bootstrap 4 模态,我想在模态关闭后将用户重定向到另一条路线。但是,当模式关闭时,我遇到了范围界定问题,告诉我注入(inject)的路由器未定义。

我的代码:

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
        })
    }
}

最佳答案

Jquery 中那样使用 this 关键字。

ngAfterViewInit() {
var self = this;
    $('#mymodal').on('hidden.bs.modal', function (e) {
        self.router.navigate(['/']);
    })
}

关于javascript - 在 Angular 中的 jQuery 事件监听器中使用注入(inject)的依赖项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52357078/

相关文章:

angular - 在 Angular 4 中,钩子(Hook) ngOnChanges 没有在输入时触发

javascript 'this' 引用了错误的范围

Javascript 函数和嵌套函数

javascript - 在另一个js中调用一个js文件的正确且最简单的方法

javascript - JQuery 旋转列表

javascript - 使用 jQuery 禁用除滚动条之外的所有点击操作

javascript - ionic 模板中的 var 未定义,但 console.log 显示它

javascript - 如果鼠标离开父元素则隐藏元素

angular - 在 Spring Boot 中从 Angular 7 的请求接收空授权 header ,但 Postman 工作正常

javascript - 如何使用 jQuery 从外部函数访问内部函数的变量?