gpt4 book ai didi

javascript - 更改触发路由器事件的导航

转载 作者:行者123 更新时间:2023-12-03 10:03:29 25 4
gpt4 key购买 nike

我想在导航开始后更改目的地路线。
如果用户单击浏览器后退按钮,我将使用我想要的 Angular 创建应用程序,我将用户导航更改为主页。在我的 app.component 我检查导航但路由器导航不会触发:

constructor(router: Router) {
router.events.subscribe((val: NavigationStart) => {
if (val.navigationTrigger === 'popstate') {
router.navigate['home'];
}
});
}

路由器事件触发后是否可以更改目标路由?
更新:
我的 AppRoutingModule 包含:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

const routes: Routes = [
{ path: 'account', loadChildren: () => import('./account/account.module').then(m => m.AccountModule) },
{ path: '', loadChildren: () => import('./home/home.module').then(m => m.HomeModule) },
{ path: 'notification', loadChildren:() => import('./notification/notification.module').then(x=> x.NotificationModule) }
];

....
export class AppRoutingModule { }

和我的例如 NotificationRoutingModule :
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { NotificationComponent } from './notification.component';
import { ListComponent } from './list/list.component';
import { DetailComponent } from './detail/detail.component';

const routes: Routes = [
{path: '' ,component: NotificationComponent,children: [
{path: '', redirectTo: 'list', pathMatch: 'full'},
{path: 'list', component: ListComponent},
{path: 'detail/:id', component: DetailComponent}
]}
];

....
export class NotificationRoutingModule { }

我的 HomeRoutindModule 包含:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home.component';

const routes: Routes = [
{path: '' , component : HomeComponent},
{path: 'home' , component : HomeComponent},
];

....
export class HomeRoutingModule { }


我想如果用户在按下浏览器导航后进入导航(“通知”),我会更改下一个导航,无论它是什么,导航更改为“主页”之类的东西。

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.sass']
})
export class AppComponent implements OnInit {
constructor(router: Router) {
router.events.subscribe((val: NavigationStart) => {
if (val.navigationTrigger === 'popstate') {
// if val.url equal '/notification/list'
router.navigate['\home'];
// i tried it but navigation does't changed
}
});
}

}

最佳答案

路由器导航方法将数组作为命令,将对象作为附加对象( NavigationExtras 接口(interface) )。和 导航附加 接口(interface)的属性为 替换网址
用于替换当前状态。然后我将代码更改为:

constructor(router: Router) {
router.events.subscribe((val: NavigationStart) => {
if (val.navigationTrigger === 'popstate') {
// here changed
router.navigate(['home'], {replaceUrl:true});
}
});
}

关于javascript - 更改触发路由器事件的导航,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59510786/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com