My module.ts,
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule,Router } from '@angular/router';
import { AppComponent } from './crud/app.component';
import { Profile } from './profile/profile';
import { Mainapp } from './demo.app';
import { Navbar } from './header/header';
// import {ToasterModule, ToasterService} from 'angular2-toaster';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
@NgModule({
imports: [ BrowserModule,FormsModule, ReactiveFormsModule ,
RouterModule.forRoot([
{ path: '', component:AppComponent},
{ path: 'login', component:AppComponent},
{ path: 'profile', component:Profile}
]) ],
declarations: [ AppComponent,Mainapp,Navbar,Profile ],
bootstrap: [ Mainapp ]
})
export class AppModule {
}
Here i want to call a function from main.ts on every route change and how can i do that.Can anyone please help me.Thanks. My mainapp.ts,
export class Mainapp {
showBeforeLogin:any = true;
showAfterLogin:any;
constructor( public router: Router) {
this.changeOfRoutes();
}
changeOfRoutes(){
if(this.router.url === '/'){
this.showAfterLogin = true;
}
}
}
I want to call this changeofRoutes() for every route change and how can i do that?Can anyone please help me.
you can call
activate
method from mainrouter-outlet
like thiswhich will call every time when route will change.
Update -
Another way to achieve the same is to subscribe to the router events even you can filter them out on the basis of navigation state may be start and end or so, for example -
You can subscribe to the
NavigationEnd
event of router, and retrieve the URL withurlAfterRedirects
method.I strongly recommend you to use the
urlAfterRedirects
, because it seems that you need toshowAfterLogin
conditionally.Let's say, you're redirecting
/test-page
to/
; and you rely onrouter.url
. In that case the app will already be redirected to/
butrouter.url
would return/test-page
and here the issue comes ('/test-page' != '/'
).Simply, make the following changes in your constructor:
You can refer:NgRx Router
Catch all 'Go' actions in ngrx effects to do things just before the route changes, or in the reducer of this action to call a function after the route changes.
You can call directive in Routes like below:
Your AuthGuard component is like below where you put your code:
auth.guard.ts
You should import AuthGuard component in app.module.ts file and should provide in providers:
app.module.ts: