Javascript 在jQuery事件侦听器中使用注入依赖项
我在Angular 6中使用Bootstrap 4模式,我想在模式关闭后将用户重定向到另一条路径。然而,当模态关闭时,我得到一个范围问题,告诉我注入的路由器未定义 我的代码:Javascript 在jQuery事件侦听器中使用注入依赖项,javascript,angular,scope,Javascript,Angular,Scope,我在Angular 6中使用Bootstrap 4模式,我想在模式关闭后将用户重定向到另一条路径。然而,当模态关闭时,我得到一个范围问题,告诉我注入的路由器未定义 我的代码: import { Component, OnInit } from '@angular/core'; declare var $: any @Component({ selector: 'app-modal', templateUrl: './modal.component.html', st
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
})
}
}
使用
this
作为注入依赖项访问路由器
,并使用箭头函数语法((e)=>{}
)将其重新缩放到正确的范围。像这样:
ngAfterViewInit() {
$('#mymodal').on('hidden.bs.modal', (e) => {
this.router.navigate(['/']);
})
}
使用
this
作为注入依赖项访问路由器
,并使用箭头函数语法((e)=>{}
)将其重新缩放到正确的范围。像这样:
ngAfterViewInit() {
$('#mymodal').on('hidden.bs.modal', (e) => {
this.router.navigate(['/']);
})
}
像在
Jquery
中那样使用this
关键字
ngAfterViewInit() {
var self = this;
$('#mymodal').on('hidden.bs.modal', function (e) {
self.router.navigate(['/']);
})
}
像在
Jquery
中那样使用this
关键字
ngAfterViewInit() {
var self = this;
$('#mymodal').on('hidden.bs.modal', function (e) {
self.router.navigate(['/']);
})
}
也尝试过,给我“this.router is undefined”请用您尝试过的最新代码更新您的问题。您尝试过上述语法(箭头函数)吗?上面的代码只适用于arrow函数,因为该函数没有自己的this。如果您使用的是传统的匿名函数“function(e){”,则需要在回调(如下面的建议)尝试之前将其分配给自定义变量,并给出“this.router is undefined”,请使用您尝试过的最新代码更新您的问题。是否使用上述语法(箭头函数)进行了尝试?上述代码仅适用于arrow函数,因为该函数没有自己的this。如果使用传统的匿名函数“function(e){”,则需要在回调之前将其分配给自定义变量(如下所示)将jQuery与Angular框架结合使用通常是一种不好的做法。我建议您尝试ng Bootstrap或ngx Bootstrap,它们是为Angular而构建的,不依赖于jQuery。将jQuery与Angular框架结合使用通常是一种不好的做法。我建议您尝试ng Bootstrap,而不是使用Bootstrap+jQuery为Angular构建的strap或ngx引导,不依赖于jQuery。