【问题标题】:Parameter not retuning in ActivatedRoute参数未在 ActivatedRoute 中重新调整
【发布时间】:2019-01-27 18:05:14
【问题描述】:

我无法从路由中获取参数,它需要调用组件内的函数,然后调用服务。

我已经将它添加到构造函数中,因为我相信如果它在 NgInit 中可能不会及时通过,但仍然没有运气。

我添加了一个console.log,它只是打印null,我可以看到它正在调用函数但没有传递参数。

我确信它是超级基本的,我只是在某个地方犯了一个错误。

app.module.ts

const appRoutes: Routes = [
  { path: '', component: AppComponent},
  { path: 'tap/:tapcode', component: AppComponent}
];

app.component.ts

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private dataService: DataService) {

    this.tapCode = this.route.snapshot.paramMap.get('tapcode');
    console.log(this.tapCode);
    this.getScreen(this.tapCode);
  }

【问题讨论】:

  • 你试过在ngOnInit()生命周期方法里面做吗?
  • @AmitChigadani 是的

标签: javascript angular routing


【解决方案1】:

问题是数据在 ActivatedRoute 中不可用,仅在 ActivationEnd 中可用,因为它是手动输入到地址栏中的。

  constructor(
    private router: Router,
    private dataService: DataService) {

      this.router.events.pipe( filter(event=> event instanceof ActivationEnd && event.snapshot.children.length == 0))
      .subscribe((event: ActivationEnd) => {
        console.log(event.snapshot.params);
      });
      }

【讨论】:

  • 谢谢!这在解析手动输入的参数时帮助了我很多。
【解决方案2】:

你能尝试像这样在 ngOnInit 中获取激活的路由快照吗?

ngOnInit(){

this.tapCode = this.route.snapshot.paramMap.get('tapcode');

    }

或者你可以像这样订阅路线;

ngOnInit() {
  this.route.paramMap.subscribe(params => {
    this.tapCode = this.route.snapshot.paramMap.get('tapcode');
  })
}

这是一个工作示例:https://stackblitz.com/edit/angular-far56b

【讨论】:

  • 无交易,订阅时仍返回 null。我已经尝试将它放在 ngInit 而不是 Constructor 下,结果相同。
  • 嘿@hylian,你能通过stackblitz分享你的代码吗?
【解决方案3】:

您可以直接在 params.tapCode 中获取路由参数。

constructor(
    private route: ActivatedRoute,
    private router: Router,
    private dataService: DataService) {

   // this.tapCode = this.route.snapshot.paramMap.get('tapcode');

    this.tapCode = this.route.snapshot.params.tapcode; //try this
    console.log(this.tapCode);
    this.getScreen(this.tapCode);
  }

参考: https://angular.io/api/router/ActivatedRouteSnapshot

【讨论】:

  • 我启用了跟踪,可以看到它被识别为 tapcode: value 但我无法将它从对象中取出 - 仍然显示为未定义。
  • 也许你试过this.route.snapshot.params['tapcode']。或者你能显示追踪的截图吗?
  • 是的,已经尝试过了。我实际上认为这可能是因为:github.com/angular/angular/issues/19420,此处附加的跟踪输出:imgur.com/a/nvTWCDl
【解决方案4】:

现在只在 app.component.ts 中改变

 constructor(
private route: ActivatedRoute,
private router: Router,
private dataService: DataService) {

this.route.paramMap.subscribe((param=>{ this.tapCode=param.get('tapcode')
}));     
console.log(this.tapCode);
this.getScreen(this.tapCode);}

【讨论】:

  • 您已经在父组件上,如果您想将数据传递给同一个组件,则必须将该组件声明为子组件
  • 没有交易 :( - 只是返回未定义。
  • 否 - 只返回空值。我相信这与 github.com/angular/angular/issues/19420
猜你喜欢
  • 2014-01-06
  • 2017-01-10
  • 2019-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多