为什么 angular 子路由除了第一次之外不渲染组件?

why angular child route not rendering component except first time?

我的 angular 项目中的组件很少。以及在一个特殊组件中呈现这些组件的子路由。当我第一次点击路由时渲染组件。但在那之后它只改变 url 参数而不渲染任何组件。

这是我的代码,

course.component.html

<div *ngIf="courses">
  <a *ngFor="let course of courses" class="btn btn-danger" color="warn" routerLink="{{ course.id }}">{{ course.title }}</a>
</div>

course.component.ts

segmentId: Object;
courses: Object;
meta_data: any;
showSpinner: boolean = true;

constructor(private route: ActivatedRoute, private data: DataService, private seo: SeoService) {

}

ngOnInit() {
    this.segmentId = this.route.snapshot.params['segment'];
    this.route.params.subscribe((params: Params) => {
        this.segmentId = params.segment
    });

    this.data.getCourses(this.segmentId).subscribe(data => {
        this.courses = data[0].courses;

        this.meta_data = data[0];

        this.showSpinner = false;

        //console.log( this.courses )
        //console.log( this.meta_data.segmentName )
    })
}

ngOnInit 每个组件实例只调用一次。所以这是正常的行为。

如果你想要实时变化,你需要像这样使用observable:

ngOnInit() {
  this.route.paramMap.pipe(
    switchMap(params => {
      this.segmentId = params.get('segment');
      return this.data.getCourses(this.segmentId);
    })
  ).subscribe(
    data => {
      this.courses = data[0].courses;
      this.meta_data = data[0];
      this.showSpinner = false;
    }
  )
}