Below are codes of my app.component.ts and another module called login. I have setup router for navigation to login component. I will first put down my code and then state my problem after that.
app.component.ts
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
constructor(private router: Router) { }
ngOnInit() {
const accessToken = localStorage.getItem('access_token');
// if(accessToken) {
// this.router.navigateByUrl('/posts');
// } else {
// this.router.navigateByUrl('/login');
// }
}
}
login.component.ts
import { Component, OnDestroy, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit, OnDestroy {
paramsSubscription: Subscription | undefined;
constructor(private route: ActivatedRoute, private router: Router) { }
ngOnInit() {
this.paramsSubscription = this.route.queryParams.subscribe(params => {
const accessToken = params['access_token'] || localStorage.getItem('access_token');
console.log('ACCESS TOKEN: ', accessToken);
if(accessToken) {
localStorage.setItem('access_token', accessToken);
}
});
}
ngOnDestroy() {
this.paramsSubscription?.unsubscribe();
}
loginViaFacebook() {
window.location.href = 'http://localhost:3000/auth/facebook';
}
loginViaGoogle() {
window.location.href = 'http://localhost:3000/auth/google';
}
}
I am trying to pass a query parameter to the /login
path and if the same is found I want to redirect the user to /posts
.
The path I am trying to access is http://localhost:4200/login?access_token=abcdef
.
There is an unexpected behaviour that I am observing. When I comment the navigation code in ngOnInit()
of app.component.ts
I am able to capture the queryParam in my login.component.ts
. However if I keep it uncommented, I can see the queryParam getting logged once and the login path is again called and this time there is no query param(It is empty).
I am new to angular. Is there something related to routers that I am missing?