2017-05-09 24 views
0

数据我有两个组成部分:成分A和成分B,其中B组份名为“过滤器”是比较A的儿童角2:子组件没有一次父组件重新初始化会从服务

他们是基于激活的路由,他们在URL中获取更改并将呼叫发送到服务器并从中获取最新的“filterMap”。

Component_A.html

<section class="abc"> 
    <filter [filterMap]=[filterMap]></filter> 
    <div *ngFor="let item of courses"> 
    <!-- code --> 
    </div> 
</section> 

Component_A.ts

import { Component, OnInit, OnDestroy } from '@angular/core'; 
import { Router, ActivatedRoute } from '@angular/router'; 
import { Subscription } from 'rxjs'; 

@Component({ 
    selector: 'component-a', 
    templateUrl: '../template/component-a.html' 
}) 

export class ComponentAComponent implements OnInit, OnDestroy { 
constructor(private _activatedRoute: ActivatedRoute, 
      private _router: Router) { } 

ngOnInit() { 
     this._querySubscription = this._activatedRoute.queryParams 
      .subscribe(params => { 
        this.setQueryParams(params); 
        this._courseService.getData() 
         .subscribe(res => { 
          if (res.data) { 
           this.courses = res.data.courseDTOList; 
           this.filterMap = res.data.filterMap; 
          } 

         });     
      }); 
    } 
} 

Component_B.html

<div class="xyz"> 
    <span> Filter Result </span> 
    <section class="filter-section" *ngFor='let filter of filterData> 
    <!-- Code --> 
    </section> 
</div> 

Component_B.ts

import { Component, Input, Output, EventEmitter, OnInit, AfterViewInit } from "@angular/core"; 
import { Router, ActivatedRoute } from '@angular/router'; 
import { Subscription } from 'rxjs'; 

@Component({ 
    selector: 'filter', 
    templateUrl: '../template/course-filter.html' 
}) 

export class FilterComponent implements OnInit{ 

@Input() filterMap: any; 

ngOnInit() { 
     if (this.filterMap[0]) 
      this.filterData = this.filterMap[0]; 
    } 
} 

问题

页面重新加载后,两个组件都会被初始化并提供所需的输出。

如果URL发生变化,则发送到服务器的调用,并且filterMap来自服务,但Component_B不会再次初始化,并且筛选器屏幕每次都保留旧数据。

+0

http://stackoverflow.com/questions/38847642/angular2-component-does-not -reinitialize-for-parameterized-route你检查过了吗? – mxr7350

回答

1

默认情况下,这是预期的行为,如果路由的参数发生变化但路由本身不包含角度重用组件。

例如对于像route/:id这样的路线,如果用户从route/1导航到route/2,则angular将重用相同的组件。

这是一个默认行为,可以通过实施您自己的RouteReuseStrategy来重写。您可以check this以获取有关此方法的更多信息。

在你的情况下,变更检测期间,而不是在限定的init组分B内的filterMap应足以:

@Component({ 
    selector: 'filter', 
    templateUrl: '../template/course-filter.html' 
}) 

export class FilterComponent implements OnChanges { 

    @Input() filterMap: any; 

    ngOnChanges() { 
    if (this.filterMap && this.filterMap[0]) 
     this.filterData = this.filterMap[0]; 
    } 
}