URL更改时Angular4重新加载组件

时间:2018-02-13 15:02:54

标签: angular

我没有找到类似问题的已接受答案,因此请不要将其标记为重复。 我有一个'request-summary'组件和'search'组件。 “搜索”组件在“请求摘要”组件中呈现为弹出窗口。我需要在搜索组件中单击匹配的结果,然后重定向到新的“请求摘要”页面。 'request-summary'订阅了URL更改并成功查看,但不会重新加载。怎么实现呢?

@Component({
  selector: 'request-summary',
  templateUrl: './request-summary.html',
  styleUrls: ['./request-summary.css'],
  encapsulation: ViewEncapsulation.None
})
export class RequestSummaryComponent {
  private subscription: Subscription;
  private requestId:number;

constructor(private documentService: DocumentService,private router: 
  Router,private activatedRoute: ActivatedRoute,private requestDist: 
  RequestDistService,private eRef: ElementRef){         
}   

ngOnInit() {   
    this.activatedRoute.params.subscribe(params => {
        this.requestId = params['requestId']
        console.log("URL id has changed")
    });
    this.getRequestInfo();  //some  logic for rendering selected request 
     info
}

搜索组件:

@Component({
  selector: 'search',
  templateUrl: './search.html',
  styleUrls: ['./search.css'],
})
export class SearchComponent {
  public userInput = '';
  private data = []

constructor(private requestDist : RequestDistService, private router: 
  Router) {   }

openSelectedGroup(id){   //click event
    this.router.navigate(['./../requestSummary/'+id]);
}

}

1 个答案:

答案 0 :(得分:3)

你实际上什么都没做,现在期望获得路线参数,将你的ngOnInit更改为它并且它会起作用

ngOnInit() {   
    this.activatedRoute.params.subscribe(params => {
        this.requestId = params['requestId']
        console.log("URL id has changed")
        this.getRequestInfo(); 
    });

}

它不是重新呈现组件本身,而是在路由更改时始终获取新数据,如果您的逻辑将包含在此订阅中。