在 Angular 2 中执行 jQuery 每个路由更改 [英] Executing jQuery each in Angular 2 on route change

查看:22
本文介绍了在 Angular 2 中执行 jQuery 每个路由更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前在 jQuery 中使用 Angular 2,jQuery 被连接到一个单独的文件中.这个文件存在于许多范围之外,范围只是一个文档就绪函数,每个特定元素都有一个

I am currently using Angular 2 with jQuery, the jQuery is concatenated into a separate file. This file exists out of many scopes, the scope is simply an on document ready function with an each on specific elements

当在正确的页面上重新加载浏览器时,代码执行得非常好,因为它确实找到了准备好的文档元素,但是当从另一个页面导航时,代码不会运行.

When reloading the browser on the correct page the code gets executed perfectly fine because it truly finds the elements on document ready, however when navigating from another page the code does not run.

我尝试通过在应用组件中设置 ngAfterViewInit() 来解决这个问题,在那里加载脚本而不是像这样在 index.html 中加载脚本:

I tried working around the problem by setting an ngAfterViewInit() in the app component, loading the script there instead of in the index.html like this:

export class AppComponent implements AfterViewInit{
    ngAfterViewInit() {
        $( document ).ready(function() {
            $.getScript( "library/js/main.min.js" );
        });
    }
}

代码再次只在特定页面上重新加载时执行,我是否需要在每个组件上添加这个 ngAfterViewInit()?

The code is again only executing when reloading on that specific page, do I need to add this ngAfterViewInit() on every single component?

推荐答案

解决方案是一个 Router 事件监听器;此代码段中的代码将侦听路由器中的更改(根据 NavigationEnd 的实例过滤),然后执行其中的代码,它使用 jQuery 检索 JavaScript 文件.

The solution was a Router event listener; the code in this snippet will listen to changes in the router (which are filtered on instances of NavigationEnd) and then executes the code inside, it retrieves a JavaScript file with jQuery.

import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';

import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/map';

declare var $:any;

export class AppComponent implements OnInit {
    constructor(
        private router: Router,
        private activatedRoute: ActivatedRoute
    ) { }

    ngOnInit() {
        this.router.events
        .filter(event => event instanceof NavigationEnd)
        .map(() => this.activatedRoute)
        .subscribe((event) => {
            $.getScript('library/js/main.min.js');
        });
    }
}

这篇关于在 Angular 2 中执行 jQuery 每个路由更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆