here is my auth.service.ts
import { Injectable } from "@angular/core";
import { GoogleAuthProvider } from 'firebase/auth';
import { AngularFireAuth } from '@angular/fire/compat/auth';
import { Observable } from "rxjs/internal/Observable";
import firebase from 'firebase/compat/app';
import { ActivatedRoute, Router, RouterLink, RouterStateSnapshot } from "@angular/router";
@Injectable({ providedIn: 'root' })
export class AuthService {
user$: Observable<firebase.User|null>;
constructor(private afAuth:AngularFireAuth, private router:Router,private route: ActivatedRoute) {
this.user$ = afAuth.authState;
}
login() {
let returnUrl = this.route.snapshot.queryParamMap.get('returnUrl') || '/';
localStorage.setItem('returnUrl',returnUrl);
this.afAuth.signInWithRedirect(new GoogleAuthProvider());
}
logout(){
this.afAuth.signOut();
}
}
and here is my app.component.ts
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from './auth.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
constructor(private auth : AuthService, router:Router){
auth.user$.subscribe(user=>{
if(user){
let returnUrl = localStorage.getItem('returnUrl');
router.navigateByUrl(returnUrl)
}
});
}
}
and the error is coming for router.navigateByUrl(returnUrl) line for returnUrl, the error is
Argument of type 'string | null' is not assignable to parameter of type 'string | UrlTree'.
Type 'null' is not assignable to type 'string | UrlTree'.
I do not know how to solve this
CodePudding user response:
Because localStorage.getItem('returnUrl') returns either string or null,
the value of returnUrl is either string or null, but the navigateByUrl method doesn't accept null as a parameter.
so you need to set it, either way - a string, you can do it by giving it a default value:
let returnUrl = localStorage.getItem('returnUrl') || 'home-page';
