2

我有 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',
  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();
    });
...
})
4

3 回答 3

3

如果您使用 CLI,则需要将该文件.angular-cli.json包含在“脚本”数组中的文件中。

如果您只想从该文件中调用一个函数 home.component.ts,那么您可以声明如下

declare var global:any; 

然后继续

ngOnInit(){
    global.InitSwiper();
}

有些人建议使用警卫,但如果您不需要延迟或防止路线被加载,那就有点过头了。

于 2017-11-27T20:13:03.373 回答
2

您可以创建一个服务并让您的路由器在 canActivate 中调用它,一旦它进入所需的路由,就像这样。这将让您在组件加载之前处理任何事情

路由器模块.ts

...
import {myService} from '../services/myService.service'
export const routes: Routes = [
  {path: '/home', component: HomeComponent, canActivate:[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) { }
于 2017-11-27T19:54:12.620 回答
2

如果您在构造函数中导入路由器,您实际上可以像这样订阅它:

import { Router, NavigationEnd } from '@angular/router';

constructor(private next: Router) {
  next.events.subscribe((route) => {
    if (route instanceof NavigationEnd) {
      console.log(route.url);
    }
  });
}

在上面的示例中,它应该打印出当前路线。

于 2017-11-27T19:04:38.960 回答