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



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

我有一个获取不同参数的组件,如下所示。但是,当输入组件路由时,它只加载一次,并且...

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;
      })
  }
}

快照值只会给你参数的第一个值 ,而是订阅this.route.params可观察量,每次路由中的参数 ID 更改时,可观察量将解析:

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

最新更新