![](/img/trans.png)
[英]TS2345: Argument of type 'string' is not assignable to parameter of type 'never'
[英]TS2345: Argument of type 'string | null' is not assignable to parameter of type 'string | UrlTree'
这个问题的标题是 Angular CLI 编译器抛出的消息。
我的 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”下划线,如果我使用上面的 cursor,它会说:
“'string | null' 类型的参数不可分配给'string | UrlTree' 类型的参数。'null' 类型不可分配给'string | UrlTree' 类型。”
我有一个与 Firebase 相关的 user.service.ts:
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
});
}
}
有没有人知道编译器的问题是什么? 我还附上了控制台消息。
该错误为您提供了所需的所有信息。
localStorage.getItem
返回一个字符串或null
,并且router.navigateByUrl
需要一个string
或UrlTree
的参数。 在调用router.navigateByUrl
之前,您必须检查 localStorage.getItem 的返回值以确保它不是 null ,因为您不能使用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);
}
您可以使用感叹号告诉编译器该值不能为 null,如下所示:
let returnUrl = localStorage.getItem('returnUrl');
router.navigateByUrl(returnUrl!);
你有线
let returnUrl = localStorage.getItem('returnUrl');
getItem()
function 返回null | string
null | string
。 如果项目不在存储中,则函数返回 null。
router.navigateByUrl(returnUrl);
期望returnUrl
的类型为string | UrlTree
string | UrlTree
但returnUrl
被推断为null | string
来自其初始化的null | string
,因此错误
有多种方法可以解决这个问题,一种简单的方法是将返回的值类型转换为字符串
let returnUrl = localStorage.getItem('returnUrl') as string;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.