我试图使用角度路由器从一个组件移动到另一个组件,但会发生以下情况:
当我在http://localhost:4200/#/home
并且我执行url的更改移动到
http://localhost:4200/#/view
同
route.navigate(["view"]) / routerLink="/view"
网址会更改,但会再次返回主页,但是当我手动将网址更改为
http: // localhost: 4200 / # / view
它完美地运作。
怎么了?
我使用以下代码
import { HomeComponent } from './home/home.component';
import { RouterModule, Routes } from '@angular/router';
import { ModuleWithProviders } from '@angular/core/src/metadata/ng_module';
import { ViewpostComponent } from './viewpost/viewpost.component';
export const AppRoutes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'view', component: ViewpostComponent }
];
export const Rutas: ModuleWithProviders = RouterModule.forRoot(AppRoutes, { useHash: true });
你的路线顺序很重要。改变这样的顺序:
export const AppRoutes: Routes = [{
path: 'home',
component: HomeComponent
},
{
path: 'view',
component: ViewpostComponent
},
{
path: '',
redirectTo: '/home',
pathMatch: 'full'
}
];
同样根据Richards的建议,如果您尝试从Component Class导航,请使用this.route.navigate(['/view']);
这是一个StackBlitz供您参考。
如果它不起作用,['view']和['/ view']都工作相同你会发布模板代码的路由导入事项的顺序并匹配使用router.navigate([])的意图当你逻辑完成将用户重定向到特定页面,如果您在家庭组件中调用router.navigate([]),您能否向我们展示代码