无法从路由 URL 读取参数

Can't read params from route URL

我试图用我的 angular-cli 项目创建一个简单的组件,它从 URL

加载参数
@Component({
  templateUrl: './confirm-registration.component.html',
})
export class ConfirmRegistrationComponent implements OnInit {

  constructor(private route: ActivatedRoute,
              private router: Router) { }

  ngOnInit() {
    this.route.params.switchMap((params: Params) => {
      return console.log('token:', params['registrationToken']);
    });
  }

}

但我收到错误:

编译失败

.../confirm-registration.component.ts (15,33): Argument of type '(params: Params) => void' is not assignable to parameter of type '(value: Params, index: number) => ObservableInput<{}>'. Type 'void' is not assignable to type 'ObservableInput<{}>'.

我用的是4.0.3版本的Angular。我哪里弄错了?

为了获取查询参数,我使用 angular-2 进行了此操作。我不确定它是否适用于 angular-4

constructor(private route: ActivatedRoute) {

}

ngOnInit() {
  let urParam = this.route.snapshot.queryParams['urParam'];
}

希望对您有所帮助

我用这个获取查询参数:

export class ConfirmRegistrationComponent implements OnInit {

private registrationToken: string;

constructor(private route: ActivatedRoute) {}

ngOnInit() {
this.route.params.subscribe(
  (params) => {
    this.registrationToken = params['registrationToken'];
  }
)

正如 dzejdzej 在他的 中指出的那样,您必须 return 一个可观察对象。这似乎在最近几个月发生了变化(至少我几个月前最后一次尝试编译了它),而且他们还没有改变文档。

因此,在您的情况下,您可以简单地 return 相同的可观察对象:

ngOnInit() {
  this.route.params.switchMap((params: Params) => {
    console.log('token:', params['registrationToken']);
    return this.route.params;
  });
}