路径操作不适用于组件和不同的参数

时间:2017-10-26 16:43:24

标签: angular angular-router

路线操作不适用于组件和不同的参数。

我有一个获得不同参数的组件,如下所示。但是,在输入组件路径时,它只加载一次......

this.route.snapshot.params [' id']未更新。

路线

export const ROUTES: Routes = [
    {path: '', component: AppComponent,
        children: [
            { path: '', redirectTo: 'home', pathMatch: 'full'},
            { path: 'home', component: HomeComponent },
            { path: 'categoria/:id', component: ListaComponent },
            { path: 'player/:id', component: PlayerComponent }]
    }]

组件

import {Component, OnInit } from '@angular/core';
import { PostServices } from '../postServices';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'net-lista',
  templateUrl: './lista.component.html',
})
export class ListaComponent implements OnInit {

    order: any;

  constructor(private postServices: PostServices, private route: ActivatedRoute) {

  }

  ngOnInit() {
      this.postServices.getPostByCategory(this.route.snapshot.params['id']).subscribe( (res) => {
          this.order = res;
      })
  }

}

1 个答案:

答案 0 :(得分:1)

快照值将为您提供参数的第一个值  而是订阅this.route.params Observable,每当路由中的参数id改变时,Observable将解析:

 ngOnInit() {
          this.route.params.subscribe((params)=>{
          this.postServices.getPostByCategory(params["id"]).subscribe( (res) => {
              this.order = res;
           })
       })
  }