【问题标题】:window.location.href vs angular2 router.navigatewindow.location.href vs angular2 router.navigate
【发布时间】: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


【解决方案1】:

你是对的,Angular 不会在路由更改时触发窗口加载。这是两个不同的东西。

说到不同的东西,JQuery 和 Angular 也是。您应该将 JQuery 与 Angular 一起使用:使用 Angular 时,您不应直接操作 DOM,而应使用框架来执行此操作。并且 JQuery 不是这个框架的一部分......

但如果你想继续这样做,那么你需要更新你的触发函数。我想现在你有类似的东西

window.onload = () => {...}

对吗?好吧,如果你想在 Angular 中监听路由变化,那么你需要订阅路由事件。

首先将路由器注入到您的组件中,然后监听路由更改事件:

constructor(private router:Router) {
  router.events.subscribe(events => {
    console.log('Angular has changed route');
  });
}

请记住,如果您将它放在路由组件中,那么一旦您更改路由,它就会被销毁。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-11
    • 2016-05-06
    • 1970-01-01
    • 2017-04-13
    • 1970-01-01
    • 2018-05-14
    • 1970-01-01
    相关资源
    最近更新 更多