不确定我丢失了什么,我有一个子崩溃,并且参数始终未定义...但是,它确实加载了正确的组件,但是以某种方式未读取参数。 (我确实看到了网址上的参数)
应用溃败
import { ModuleWithProviders, NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { DashboardComponent } from './dashboard/dashboard.component';
// these would equal welcome component
const routes: Routes = [
{ path: '', redirectTo: 'dashboard', pathMatch: 'full' },
{ path: 'dashboard', component: DashboardComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
搜索溃败
import { ModuleWithProviders, NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { SearchComponent } from '../search/search.component';
const routes: Routes = [
{ path: 'search', component: SearchComponent,
children: [
{ path: ':id/:name', component: SearchComponent }
]
},
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class SearchRoutingModule { }
search.component (我尝试了两个快照都可以观察到)
console.log('id ===========>' + this._rout.snapshot.params['id']);
this._rout.params.subscribe(params => {
console.log('id2 ===========>' + params['id']);
});
search.module
import { NgModule } from '@angular/core';
import { SearchComponent } from '../search/search.component'
import { HttpModule } from '@angular/http';
import { BrowserModule } from '@angular/platform-browser';
from '@angular/forms';
import { SearchRoutingModule } from './search.routing';
@NgModule({
imports: [HttpModule, BrowserModule, SearchRoutingModule
],
declarations: [SearchComponent],
providers: [SearchService],
exports: []
})
export class SearchModule { }
应用模块
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app.routing';
import { HttpModule } from '@angular/http';
import { CommonModule } from '@angular/common';
import { SearchModule } from './search/search.module';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule, HttpModule, SearchModule, AppRoutingModule, CommonModule
],
providers: [AppComponentService],
bootstrap: [AppComponent]
})
export class AppModule { }
答案 0 :(得分:1)
在您的params
中未收到SearchComponent
的问题是,parent
路由和child
路由都指向相同的component
。
Angular正在为parent
路由加载组件(不带参数),但是url仍然指向child
路由,因为angular已找到针对它配置的路由,但自从加载以来没有成功在父级内部未找到任何router-outlet
。
使它成为child
路由的兄弟路由,而不是进行parent
路由。它加载得很好。
您可以通过这种方式重新配置路由
{ path: 'search', component : SearchComponent, pathMatch : 'prefix'},
{ path: 'search/:id/:name', component: SearchComponent }
请参阅此stackblitz供参考
编辑:
如果您在<router-outlet>
中添加SearchComponent
,它将与您当前的路线一起使用,但是它将在嵌套中加载相同的组件。一个给父母,一个给孩子。
相反,您可以为SearchModule
创建另一个DummyComponent
的根组件,将其激活为父路由,然后将其中的所有子组件加载到其中。