我有一个5角web应用程序,我需要在单独的组件中单独进行路由。
这是我的项目结构:
app.module.ts:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { Help1Component } from '...';
import { HomeComponent } from '...';
@NgModule({
declarations: [
AppComponent,
HomeComponent,
Help1Component
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
APP-routing.module.ts:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from '...';
import { Help1Component } from '...';
const routes: Routes = [
{
path: 'help1',
component: Help1Component,
outlet: 'home'
},
{
path: '',
component: HomeComponent
}
]
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
app.component.html:
<router-outlet></router-outlet>
home.component.html:
<ul class="sub">
<li><a href="javascript:void(0);" (click)="helpPages('help1')"></li>
<other links here>
</ul>
<some other html>
<router-outlet name="home"></router-outlet>
<some other html>
home.component.ts:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
constructor(
private _router: Router) { }
ngOnInit() {}
helpPages(routeName:string) {
this._router.navigate([{ outlets: { home: [ routeName ] }}])
}
}
主组件有一个命名路由器插座(主页),用于从导航菜单中加载内容页面。因此,每当我点击帮助菜单时,它应该在home.component上的路由器插座上加载,而不是在app.component上的主要插件上加载
然后在我的home.component.ts上,我有这段代码:
helpPages(routeName:string) {
this._router.navigate([{ outlets: { home: [ routeName ] }}])
}
routeName 可以是已映射到home的任何路由,在本例中为帮助页面。
{
path: 'help1',
component: Help1Component,
outlet: 'home'
}
但是在调用方法时,我得到一个错误:
SyntaxError:意外的令牌)
我不明白。我相信我的代码是正确的,编译得很好,没有任何问题。我已经对这个问题进行了几天的讨论,检查每个教程,论坛和堆栈溢出以寻找可能的解决方案,但无济于事。
但是当我将<router-outlet name="home">
放在app.component.html
上,就在另一个路由器插座的下方时,页面加载就可以了。
我没有得到的是为什么它在app.component.html
以外的单独组件上不起作用。
我甚至尝试将NgModule
,Router
,Routes
和RouterModule
导入我的home.component
,但仍无效。
感谢您提前寻求帮助。
更新:SyntaxError: Unexpected token )
问题是在假定的通话结束时附加#
或:1
的Chrome浏览器问题。这已被标记为Chrome v65
中的错误,应根据Google帖子在v66中修复。
答案 0 :(得分:1)
我试图产生错误。我不明白。我试着让你的路由工作。因为,它是默认路径。我做不到。 如果将home组件的路径更改为home,将默认路径重定向到home route,则可以正常工作。您可以查看示例here
我对你的app-routing.module.ts所做的更改
const routes: Routes = [
{
path: '',
redirectTo: 'home',
pathMatch: 'full'
},
{
path: 'home',
component: HomeComponent,
children: [
{
path: 'help1',
component: Help1Component,
outlet: 'home'
},
]
}
]
和你的home.component.ts
helpPages(routeName:string) {
this._router.navigate([ '/home', { outlets: { home: [ routeName ] }}]);
}
我将更新您关于子路由无法在默认路径上工作的原因。
答案 1 :(得分:0)
尝试从
更改重定向方法 this._router.navigate([{ outlets: { home: [ routeName ] }}])
到
this.router.navigateByUrl('/(home:help1)');
并告诉我它是否有效。