【问题标题】:Angular routing doesn't refresh the page角度路由不刷新页面
【发布时间】:2021-08-12 07:56:34
【问题描述】:

我希望能够根据 URL 路由更改页面上的数据,即 test/1 获取我的数据集 1,test/2 获取我的数据集 2。但是,如果我已经在 test/1 上并尝试要使用路由器导航导航到 test/2(反之亦然),它会更改 url 但仅此而已,不会触发其他任何内容。

我的路线有以下定义:

const routes: Routes = [
  {
    path: 'test',
    children: [
      {
        path: ':id',
        component: TestComponent
      },
      { path: '**', redirectTo: '', pathMatch: 'full' }
    ]
  },
];

TS 组件:

value: any;

constructor(private router: Router, private, private route: ActivatedRoute) { 
   this.value = this.route.snapshot.params.id;
}

goToPage(value: any) {
    this.router.navigate(['/test', value]);
}

我的 html 组件:

{{value}}

<button (click)="goToPage(1)">One</button>
<button (click)="goToPage(2)">Two</button>

我也尝试将 { onSameUrlNavigation: 'reload' } 添加到 RouterModule.forRoot,但仍然没有做任何事情。

注意: 问题不在于获取参数,问题在于必须刷新页面才能触发与新参数关联的所有进程。

【问题讨论】:

    标签: angular


    【解决方案1】:

    选项1:监听路由变化并初始化页面

    constructor(private router: Router, private, private route: ActivatedRoute) {
       this.value = this.route.snapshot.params.id; // for first entry
       route.params.subscribe(val => {
         this.value = this.route.snapshot.params.id;
         // put the code to initialize the page
       });
    
    }
    

    选项 2:重新初始化路线导航页面

    goToPage(value: any) {
        this.router.routeReuseStrategy.shouldReuseRoute = function () {
            return false;
        }
        this.router.onSameUrlNavigation = 'reload';
        this.router.navigate(['/test', value]);
    }
    

    【讨论】:

      【解决方案2】:

      您可以订阅paramMap 并获取id,而不是从this.value = this.route.snapshot.params.id 获取参数

      this.route.paramMap.subscribe(
        (params: ParamMap) => {
          const id = params.get('id');
      
          // call your api etc to get the record against new id
        }
      );
      

      【讨论】:

      • 是的,已经使用了该方法,但是如何解决页面刷新问题?
      • @Aeseir 每次路线更改时都会订阅,您将获得新的路线值,我相信我首先发布了这个答案,所以您应该接受我的尝试:) 无论如何您都可以投票
      【解决方案3】:

      为了能够刷新数据,这段代码this.value = this.route.snapshot.params.id应该以这种方式在ngOnInit()中调用:

        ngOnInit() {
          this.activatedRoute.params.subscribe(
            param => {
              this.value = param['id']
              }
            }
          );
        }
      

      【讨论】:

      • 是的,已经使用了该方法,但是如何解决页面刷新问题?
      • 刷新地址here
      【解决方案4】:

      通过实现以下代码解决了问题:

          this.router.navigate(['/test', value])
              .then(() => {
                window.location.reload();
              });
      

      【讨论】:

        猜你喜欢
        • 2022-01-05
        • 1970-01-01
        • 2020-02-23
        • 1970-01-01
        • 1970-01-01
        • 2020-04-25
        • 2019-01-24
        • 2018-10-12
        • 2016-10-23
        相关资源
        最近更新 更多