角度5。如何在Javascript文件中跟踪路由更改,或在组件级别执行函数?
我有global.js脚本文件,需要在路由更改为“/home”时启动InitSwiper()函数,但找不到如何在脚本文件中跟踪路由器或通过home.component.ts启动函数角度5。如何在Javascript文件中跟踪路由更改,或在组件级别执行函数?,javascript,angular,typescript,angular4-router,Javascript,Angular,Typescript,Angular4 Router,我有global.js脚本文件,需要在路由更改为“/home”时启动InitSwiper()函数,但找不到如何在脚本文件中跟踪路由器或通过home.component.ts启动函数 import { Component, OnInit } from '@angular/core'; declare var global: any; @Component({ selector: 'app-home', templateUrl: './home.component.html', s
import { Component, OnInit } from '@angular/core';
declare var global: any;
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
ngOnInit() {
global.initSwiper();
}
}
global.js
$(function () {
"use strict";
$(window).load(function(){
pageCalculations();
$('#loader-wrapper').fadeOut();
$('body').addClass('loaded');
initSwiper();
});
...
})
如果您在构造函数中导入路由器,您实际上可以像这样订阅它:
import { Router, NavigationEnd } from '@angular/router';
constructor(private next: Router) {
next.events.subscribe((route) => {
if (route instanceof NavigationEnd) {
console.log(route.url);
}
});
}
在上面的示例中,它应该打印出当前路由。您可以创建一个服务,并让您的路由器在到达所需路由后在canActivate中调用它,就像这样。这将允许您在加载组件之前处理任何事情 路由器.module.ts
...
import {myService} from '../services/myService.service'
export const routes: Routes = [
{path: '/home', component: HomeComponent, canActivate:[myService]}
]
...
myService.service.ts
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
@Injectable()
export class myService implements canActivate{
canActivate{
//execute initSwiper here
if(/*success?*/){
return true;
}
else{
//redirect?
}
constructor(
private _router: Router) { }
如果您正在使用CLI,则需要将该文件包含在“脚本”数组中的
.angular CLI.json
文件中
如果您只想从home.component.ts
中的该文件调用函数,那么您可以如下声明
declare var global:any;
然后
ngOnInit(){
global.InitSwiper();
}
有些人建议使用防护,但如果您不需要延迟或阻止加载路由,这就太过分了。这将失败,因为您指定路由数组的方式与每个路由objectDerp的架构不匹配,可能不是解决此问题的最佳解决方案。初始化开关可以在canActivate内工作。我将编辑这个家伙,以反映我的问题不是在组件中查找路由,而是在组件中执行函数。根据问题,只有在路由加载后才应调用initSwipe抱歉,我说错了,是的,这应该可以工作,而且比guards更简单。似乎OP不需要阻止路线加载(或延迟加载)的功能,因此这可能是最好的答案。@RRForUI非常感谢,不知道我还能坐多少小时。@EimisGenčiauskas听到这个消息很高兴。如果它对你有帮助,请把它标记为答案。