The title of this question is the message what the Angular CLI compiler throws.
I have this constructor in my app.component.ts:
export class AppComponent {
constructor(private userService: UserService, private auth: AuthService, router: Router) {
auth.user$.subscribe(user => {
if (user) {
userService.save(user);
let returnUrl = localStorage.getItem('returnUrl');
router.navigateByUrl(returnUrl);
}
});
}
}
In the above attached code part I have the 'returnURL' underlined and if I take the cursor above it says:
"Argument of type 'string | null' is not assignable to parameter of type 'string | UrlTree'. Type 'null' is not assignable to type 'string | UrlTree'."
I have a user.service.ts which is related to Firebase:
import { Injectable } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';
import * as firebase from 'firebase';
@Injectable()
export class UserService {
constructor(private db: AngularFireDatabase) { }
save(user: firebase.User) {
this.db.object('/users/' + user.uid).update({
name: user.displayName,
email: user.email
});
}
}
Does anyone has an idea about what is the compiler's problem here? I also attached the console message.
You have the line
let returnUrl = localStorage.getItem('returnUrl');
The getItem()
function returns a null | string
. If the item is not in the storage, the funtion returns null.
router.navigateByUrl(returnUrl);
expects returnUrl
to be of type string | UrlTree
but returnUrl
is infered as null | string
from its initialization hence the error
There are various ways you can resolve this, a simple one would be to typecast the returned value to a string
let returnUrl = localStorage.getItem('returnUrl') as string;
The error is giving you all of the information you need.
localStorage.getItem
returns either a string or null
, and router.navigateByUrl
expects a parameter of either a string
or a UrlTree
. You'll have to check the return value of localStorage.getItem to make sure it's not null before calling router.navigateByUrl
because you can't call it with null
.
let returnUrl = localStorage.getItem('returnUrl');
if (returnUrl) { // i.e, not null and not empty string
// now returnUrl cannot be null, so it must be a string, which is valid to use in this call
router.navigateByUrl(returnUrl);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With