更改路线时在Angular 2中分别执行jQuery [英] Executing jQuery each in Angular 2 on route change

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

问题描述

我目前正在将Angular 2与jQuery一起使用,将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天全站免登陆