【问题标题】:Cannot match any routes. Angular2 URL with parameters无法匹配任何路由。带参数的 Angular2 URL
【发布时间】: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


    【解决方案1】:

    它在控制台中记录对象的原因是对象是可变的。它可以在你的代码中的某个地方发生变化,并且日志将打印它的“最漂亮”的版本。

    如果您登录 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,它将是未定义的,因为您已经猜到:路由更改是一个异步操作。

    【讨论】:

    • 我测试了您的解决方案,但它不起作用。即使在 switchMap() 内部,它也给了我未定义的信息。我真的不明白发生了什么。
    • @RadouaneROUFID console.log(params);switchMap 中记录了什么?
    • 它记录:{"_isScalar":false,"observers":[],"closed":false,"isStopped":false,"hasError":false,"thrownError":null,"_value":{"worker":"toto","address":"114 bis Boulevard Raymond Poincaré"}}
    • 你是对的。有什么不对劲。它不会安慰任何东西。我认为switchMap里面的代码没有被执行。
    • 啊,好吧,我错过了这一部分。非常感谢你。你真的花时间来帮助我。我很感激。
    猜你喜欢
    • 2016-11-07
    • 1970-01-01
    • 1970-01-01
    • 2019-06-16
    • 2016-10-08
    • 2017-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多