簡體   English   中英

無法匹配任何路由。 帶參數的 Angular2 URL

[英]Cannot match any routes. Angular2 URL with parameters

我有一個帶有基本形式的Home組件。 當用戶提交表單時,我想將它重定向到帶有 URL 中一些信息的Search組件。

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); 我發現我的參數如下:

圖片在這里

它在控制台中記錄對象的原因是對象是可變的。 它可以在您的代碼中的某處更改,並且日志將打印它的“最漂亮”版本。

如果您登錄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 ,它將是未定義的,因為正如您所猜測的:路由更改是一個異步操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM