如何在单击按钮时更改激活路由的参数

How to change the parameter of activated Route on button click

基本上,我有两个组件 TodosComponentTodoDetailsComponent。单击 TodosComponent 中的项目会将我带到 TodoDetailsComponent,我在其中获取参数并从 API 中获取所需的数据。一切正常。

但我想在我的 TodoDetailsComponent 上制作一个下一步按钮,以便传递给参数的 id 发生变化,并且我根据订阅 activatedRoute 参数的参数获得所需的结果。我 google(d) 和 Whosebug(ed) 很多,但无法找到给我指导的示例。 Here 是问题的工作演示。如果需要更多信息,请告诉我。无论是否可能,任何信息都会有所帮助。

TodoDetails.component.ts

@Component({
  template: `<p>Todo Details Component</p>
    <div>{{ todo | json }}</div>
    <button type="button" (click)="next()">Next</button>
  `
})

export class TodoDetailsComponent implements OnInit{
  todo;
  constructor(private activatedRoute: ActivatedRoute, private service: Service) { }

  ngOnInit() { 
    this.activatedRoute.paramMap.pipe(
      switchMap(params => this.getTodo(+params.get('id')))
    ).subscribe(todo => this.todo = todo);
  }

  getTodo(id) {
    return this.service.getTodo(id);
  }

  next() {
    // if i grab the id over here and increment 
    // by id++ the id increases but as can be seen 
    // parameter is still the same, so won't work
  }

如果您更改 id 的值,您的路线将保持不变,您可以尝试使用 Router 导航到您想要的 id

你可以利用这个demo

只需更改 id 即可尝试导航到同一组件 prams

export class TodoDetailsComponent implements OnInit{
  todo;
  id: number;
  constructor(private activatedRoute: ActivatedRoute, private service: Service, 
              private router : Router) { }

  ngOnInit() { 
    this.activatedRoute.paramMap.pipe(
      switchMap(params => {
          this.id = +params.get('id')
          return this.getTodo(this.id)
      })
    ).subscribe(todo => this.todo = todo);
  }

  getTodo(id) {
    return this.service.getTodo(id);
  }

  next() {
    this.id += 1;
    this.router.navigate(['/todos',this.id]);
  } 

希望这能奏效谢谢 - 编码愉快!!