Eimis Genčiauskas
Eimis Genčiauskas

Reputation: 85

Angular 5. How to track route change in Javascript file, or execute function in component level?

I have global.js script file and need to launch InitSwiper() function when route changes to '/home', but can't find how to track router in script file or launch function through 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();
    });
...
})

Upvotes: 2

Views: 1808

Answers (3)

Rohit Ramname
Rohit Ramname

Reputation: 834

If you are using CLI, you need to include that file in .angular-cli.json file inside "scripts" array.

if you want to call a function from that file in home.component.ts only, then you can declare as below

declare var global:any; 

and then on

ngOnInit(){
    global.InitSwiper();
}

Some have suggested guards, but it's overkill if you don't need to delay or prevent the route from being loaded.

Upvotes: 3

Surreal
Surreal

Reputation: 1047

You can create a service and have your router call it in the canActivate once it goes to the required route like so. This will let you handle anything before the component gets loaded

router.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) { }

Upvotes: 2

OArnarsson
OArnarsson

Reputation: 960

If you import router in your constructor you can actually subscribe it like so:

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

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

In the example above it should print out the current route.

Upvotes: 2

Related Questions