Angular 4: Activate route with empty route param yields error: 'You provided 'null' where a stream was expected...'

Angular 4: Activate route with empty route param yields error: 'You provided 'null' where a stream was expected...'

如果我去/my/route/8000

有效。

但是如果我尝试在没有路由参数的情况下前往 /my/route,我会得到一个错误:

You provided 'null' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.

ngOnInit() {
  // the observable method
  this.route.paramMap
     .switchMap((params: ParamMap) => {
        this.number = params.get('number');
        return params.get('number');
     })
     .subscribe((number) => { return; });
}

路线

export const routes: Routes = [{
   path    : 'my',
   children: [{
      path      : '',
      pathMatch : 'full',
      redirectTo: 'route'
   },  {
      path     : 'route',
      component: SubscriberRegisterComponent, 
   }, {
      path     : 'route/:number', // gets the route parameters
      component: SubscriberRegisterComponent,
   }]
}];

为什么没有路由参数我不能直接访问我的路由?

如果我将上面的可观察方法注释掉并使用 the no-observable method 那么我可以使用空参数访问我的路线

  this.number = this.route.snapshot.paramMap.get('number ');

.switchMap() 接受一个应该 return Observable 的函数。相反,您 returning 参数值:

  this.route.paramMap
     .switchMap((params: ParamMap) => {
        this.number = params.get('number');
        return params.get('number');
     })

您还使用 switchMap 来完成工作(设置 class 属性)但是 Observables 是为在订阅方法中完成的工作而设计的(或.do() 运算符)。改为这样做:

this.route.paramMap.subscribe( (params:ParamMap) => {
    this.number = +params.get('number');
 });

顺便说一句,如果你的路由有时带参数有时不带参数,你不需要定义它两次!可选参数并不意味着包含在路由定义中。只要保持:

{
  path     : 'route',
  component: SubscriberRegisterComponent, 
}

并了解如何使用可选参数。 paramMap 仍然可以使用它们。 See the docs