【发布时间】:2018-03-09 12:17:32
【问题描述】:
我是 Angular 的新手(今天是 2018 年 3 月 9 日,是第 8 天)。
我有一个需要在窗口加载事件上执行的 jquery 方法。当我执行 this.router.navigate(['/student-consent']) 或单击浏览器上的导航按钮以访问 url /student-consent 时,从我的角度组件窗口加载事件未触发,因此我的方法未运行。
但是,当我执行window.location.href = '/student-consent' 时,我的方法正在运行。
我对此进行了一些研究,我发现在 Angular 路由导航或浏览器导航(在 Angular 应用程序中使用路由)不加载窗口,而是在 router-outlet 中加载相关的 html(组件)。
相反,在浏览器中刷新页面或直接点击 url 会执行这些情况下确实发生窗口加载事件的方法。
我的问题:有什么方法可以在路由更改时执行我的方法或在路由更改时触发窗口加载事件?
更新:根据设计限制,在我的组织中不允许在 onAfterViewInit 或任何组件生命周期挂钩中执行 jquery 方法。
js 中的窗口加载事件处理程序 -
$(window).on("load", function () {
$(".preloader").fadeOut(1000);
});
我的组件中的相关 Html 代码 -
<div class="preloader"></div>
组件 -
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import * as $ from 'jquery';
@Component({
selector: 'app-student-login-creation',
templateUrl: './student-login-creation.component.html',
styleUrls: ['./student-login-creation.component.css']
})
export class StudentLoginCreationComponent implements OnInit {
constructor(private router: Router) { }
ngOnInit() {
//$(window).trigger('routeChange');
}
createId() {
console.log('student login');
// window.location.href = '/student-consent';
this.router.navigate(['/student-consent']);
}
}
【问题讨论】:
-
请放入相关代码,您可能希望将您的 window.load 逻辑放入 onInit 生命周期钩子中,但我们需要更多代码
-
添加代码和限制
-
去掉/
this.router.navigate(['student-consent']);试试
标签: angular angular-router window-load