将页面状态作为参数保存到当前路由

Saving page state to current route as parameter

有关如何将有关特定页面状态的某些信息直接保存在 url 中作为 url 参数的任何线索。

考虑到这个stackblitz

我希望每次选择食物时 url 都会更新参数 ?favouriteFood=selectedFood

当然,如果存在此类参数,将在 ngInit() 上使用以初始化页面状态。

我已经更新了您的 StackBlitz 示例 here

以下是关键步骤:

  1. 将 Angular RouterModule 导入您的应用程序:

    @NgModule({
      imports: [
         RouterModule.forRoot([])
       ]
     })
     export class AppModule {}
    
  2. 监听路由查询参数变化来自ActivatedRoute:

    ngOnInit() {
       // Remember to unsubscribe when this component is destroyed
       this.route.queryParams.subscribe(params => {
         const selectedFood = this.foods.find(f => f.value === params.food);
         if (selectedFood) {
           this.selectedFood = selectedFood;
         }
      });
    }
    
  3. 当用户使用 Router.navigate 更改可用选项的选择时更新 URL:

    foodSelectionChange(change: MatSelectChange) {
      const food: Food = change.value;
      this.router.navigate([], { 
        queryParams: { food: food.value }
      });
    }
    

尝试使用 replaceState

import {Location} from '@angular/common';

@Component({
  selector: 'example-component',
  templateUrl: 'example.component.html'
})
export class ExampleComponent
{
  constructor( private location: Location )
  {}

  setTheFood()
  {    
    this.location.replaceState('favouriteFood=selectedFood');
  }
}