我有一个带有基本表单的 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 }]);
}
}
我的SearchComponent
@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
中的参数值时,我得到未定义
。但是当我“控制台”console.log(this.route.params);
时,我发现我的参数如下:
最佳答案
它在控制台中记录对象的原因是对象是可变的。它可以更改代码中的某个位置,并且日志将打印它的“最漂亮”版本。
如果您记录 console.log(JSON.stringify(this.route.params));
我非常希望 if 再次未定义。
正确的方法如下:
let add = this.route.params
.subscribe((params: Params) => {
selectedWorker = +params['worker'];
console.log(selectedWorker); //defined
return null;
});
console.log(selectedWorker); // undefined
但是,如果您在其下方记录 selectedWorker
,它将是未定义的,因为正如您所猜测的:路由更改是一个异步操作。
关于javascript - 无法匹配任何路线。带参数的 Angular2 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41524789/