[英]Type '{}' is not assignable to type 'string'
我正在使用ngrx / router 。
当我打开http://localhost/set-new-password/abc
, RouteParams
运行良好。 我可以获得我想要的字符串token
。
const landingRouter: Routes = [
{ path: '/set-new-password/:token', component: SetNewPasswordComponent },
];
export class SetNewPasswordComponent implements OnInit {
token: string = '';
constructor(private _routeParams$: RouteParams) {}
ngOnInit()
{
this._routeParams$
.pluck('token')
.subscribe(token => {
console.log(typeof token); // Console: "string"
console.log(token); // Console: "abc"
this.token = token; // Terminal: Type '{}' is not assignable to type 'string'.
});
}
}
但是,我在终端中收到以下警告:
类型“ {}”不可分配给类型“字符串”。
我知道我可以使用this.token = String(token);
摆脱它。
但是为什么显示此警告? 有人可以帮我解释一下吗? 谢谢
从@brandonroberts获得帮助,以@ MikeRyan52的原始答案,谢谢!
这样做不起作用的两个原因:
实际上,直到运行时我们才知道params对象的形状,因此没有一个好的类型来描述它
由于字符串选择器未知,因此pluck('id')仍然无法正确键入
解决方案是显式键入pluck():
params$.pluck<string>('id')
所以我的情况变成了:
this._routeParams$
.pluck<string>('token')
.subscribe(token => this.token = token);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.