类型"{}"不能指定为"字符串"类型

Hon*_*iao 2 router typescript rxjs5 ngrx angular

我正在使用ngrx /路由器.

当我打开时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'.
      });
  }
}
Run Code Online (Sandbox Code Playgroud)

但是,我在终端收到了这个警告:

类型"{}"不能指定为"string"类型.

我知道我可以this.token = String(token);用来摆脱它.

但为什么这个警告显示出来?有人可以为我解释一下吗?谢谢

Hon*_*iao 5

从@brandonroberts获取帮助@ MikeRyan52的原始答案,谢谢!

这不起作用的两个原因:

  1. 我们实际上并不知道params对象的形状直到运行时,所以没有一个好的类型来描述它

  2. pluck('id')无论如何都不能很好地输入,因为字符串选择器是未知的

解决方案是显式输入pluck():

params$.pluck<string>('id')
Run Code Online (Sandbox Code Playgroud)

所以我的情况正在变为:

this._routeParams$
  .pluck<string>('token')
  .subscribe(token => this.token = token);
Run Code Online (Sandbox Code Playgroud)