【发布时间】:2017-01-07 18:11:50
【问题描述】:
我有一个带有基本表单的Home 组件。当用户提交表单时,我想将其重定向到 Search 组件,并在 URL 中包含一些信息。
我的HomeComponent:
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
worker: string;
address: string;
constructor(private router: Router) { }
ngOnInit() {
}
doSearch() {
this.router.navigate(['/search', { worker: this.worker, address: this.address }]);
}
}
我的搜索组件
@Component({
selector: 'app-search',
templateUrl: './search.component.html',
styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit {
constructor(private router: Router, private route: ActivatedRoute) { }
ngOnInit() {
let selectedWorker: string;
console.log(this.route.params); //
console.log(this.route.params['worker']); // undefined
let add = this.route.params
.switchMap((params: Params) => {
console.log(params);
selectedWorker = params['worker'];
console.log(selectedWorker); //defined
return null;
});
console.log(selectedWorker); // undefined
}
}
还有路由模块:
const appRoutes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'search', component: SearchComponent },
{ path: 'signup', component: SignupComponent },
{ path: '', redirectTo: '/', pathMatch: 'full' },
{ path: '**', component: PageNotFoundComponent }
];
@NgModule({
imports: [
RouterModule.forRoot(appRoutes)
],
exports: [
RouterModule
]
})
export class AppRoutingModule { }
我的问题是当我想检索SearchComponent 中的参数值时,我得到undefined。但是当我“控制台”console.log(this.route.params); 时,我发现我的参数如下:
【问题讨论】:
标签: javascript angular typescript angular2-routing