'how to create "ngOnActive" life cycle hook in angular?
I want a life cycle hook to be called when ever my component is active on the main page.
its login page.
when ever my component is on the main page i.e is active i want to see if i already have login token from previous login and depending on the result i want to navigate to different page.
is there any `ngOnActive' hook if not then how to create it?
or is there is any other way to achieve this?
my code:
import { Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';
import {LoginService} from './login.service';
import {TokenService} from '../data/token.service';
import {Router} from '@angular/router';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css'],
providers: [LoginService]
})
export class LoginComponent implements OnInit {
constructor(private loginService: LoginService, private tokenService: TokenService, private router: Router) { }
ngOnInit() {
if (this.tokenService.getToken() !== '') {
console.log(this.tokenService.tk);
this.router.navigate(['/admin']);
}
}
onSubmit(form: NgForm) {
this.loginService.login(form.value.email, form.value.password);
}
}
Solution 1:[1]
You can use one trick to do this, and that is detect a route change.
import { ActivatedRoute } from '@angular/router';
constructor(
private routerActive:ActivatedRoute
) {}
ngOnInit() {
this.routerActive.paramMap.subscribe(paramMap => {
if (this.router.url === "/yourURL") {
// ***** This runs whenever your page is displayed ******
}
})
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mehrshad Farzaneh |
