6

我正在开发一个带有路由和路径参数的角度应用程序。通过单击按钮,将调用一个函数以将用户重定向到具有相同路径参数的新 URL。虽然浏览器中的 URL 发生了变化,但是 app-routing.module.ts 中定义的相应组件并没有被加载。如果我再次刷新页面,则会呈现正确的页面。

这个想法是让学生获得一个带有哈希令牌(例如/student/33192c29aa8e449e94f3a1c4eef43ca8)的唯一 URL,这向他展示了一些指导方针。然后点击一下,他应该被转发到具有相同令牌的注册页面(例如/student/registration/33192c29aa8e449e94f3a1c4eef43ca8

应用程序路由.module.ts

const routes: Routes = [
  ...
  { path: 'student/registration/:token', component: RegistrationsComponent },
  { path: 'student/:token', component: GuidelinesComponent },
  ...
];

指南.component.html

forwardToRegistration(): void {
  this.router.navigateByUrl('/student/registration/' + this.studentToken);
}

URL 在浏览器中正确更新,但 RegistrationComponent 未呈现。

谢谢您的帮助!

4

3 回答 3

1

我有同样的问题,并想通了。也许您看不到内容更改,因为您在 app.component.html 中没有 router-outlet 标记。url会改变内容

<router-outlet></router-outlet>

所以你应该将 router-outlet 标签放在 app.component.html 中。

于 2020-12-11T10:27:49.203 回答
0

我通过监听应该刷新的组件中的路由器更改来解决它。

步骤 1. 在app.component.ts 中:导航到组件(孤儿)并传递一个带有变量 tableName 的对象。

this.router.navigate(['/orphan', {table:tableName} ]);

步骤 2. 在orphan.component.ts中,下标 observable 以检测路由器更改并从快照对象中获取 tableName:

constructor( private route:ActivatedRoute, private router:Router) { 
      /* Listen for router events through the observable */
      router.events.subscribe( (data) => {
        // get the data from the snapshot
        this.tableName = this.route.snapshot.params.table;
      })
}

现在使用 tableName 值刷新组件 Orphan。

于 2021-11-07T17:27:38.673 回答
0

嗯。Maybestudent/registration与默认pathMatch: 'prefix'设置相结合,使 Angular 路由器将您解释navigateByUrl为相同的路径导航。只是一个假设。

要测试这一点,请将其添加pathMatch: full到第二条路线:

{
    path: 'student/:token',
    component: GuidelinesComponent,
    pathMatch: 'full',
}
于 2020-07-21T20:34:01.837 回答