无法匹配任何路线。带参数的Angular2 URL

时间:2017-01-07 18:11:50

标签: javascript angular typescript angular2-routing

我有一个基本表单的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我得到undefined时,我想要检索参数的值。但当我'控制'console.log(this.route.params);时,我发现我的参数如下:

Image here

1 个答案:

答案 0 :(得分:1)

它在控制台中记录对象的原因是对象是可变的。它可以在代码中的某处更改,日志将打印出最美丽的#34;版本。

如果您记录console.log(JSON.stringify(this.route.params));,我非常期望再次定义。

正确的方法就像你在下面做的那样:

let add = this.route.params
     .subscribe((params: Params) => {
       selectedWorker = +params['worker'];
       console.log(selectedWorker); //defined
       return null;
     });
console.log(selectedWorker); // undefined

但是如果你在它下面记录selectedWorker它将是未定义的,因为你已经猜到:路由更改是一个异步操作。