TS2345:“字符串"类型的参数 |null' 不能分配给类型为 'string | 的参数网址树' [英] TS2345: Argument of type 'string | null' is not assignable to parameter of type 'string | UrlTree'
问题描述
这个问题的标题是 Angular CLI 编译器抛出的信息.
The title of this question is the message what the Angular CLI compiler throws.
我的 app.component.ts 中有这个构造函数:
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);
}
});
}
}
在上面附加的代码部分中,我有下划线的returnURL",如果我将光标放在上面,它会说:
In the above attached code part I have the 'returnURL' underlined and if I take the cursor above it says:
"'string 类型的参数 |null' 不可分配给类型为 'string | 的参数 |网址树'.类型 'null' 不能分配给类型 'string |UrlTree'."
"Argument of type 'string | null' is not assignable to parameter of type 'string | UrlTree'. Type 'null' is not assignable to type 'string | UrlTree'."
我有一个与 Firebase 相关的 user.service.ts:
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.
推荐答案
该错误为您提供了所需的所有信息.
The error is giving you all of the information you need.
localStorage.getItem
返回字符串或 null
,并且 router.navigateByUrl
需要 string
的参数code> 或 UrlTree
.在调用 router.navigateByUrl
之前,您必须检查 localStorage.getItem 的返回值以确保它不为 null,因为您不能使用 null
调用它.>
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);
}
这篇关于TS2345:“字符串"类型的参数 |null' 不能分配给类型为 'string | 的参数网址树'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!