在angular4中重新加载具有不同路径参数的组件

时间:2017-08-03 11:09:28

标签: angular angular-routing angular-router

我正在使用angular2路由。当用户在搜索字段中重新输入值并单击搜索时,需要重新加载相同的组件,但需要使用不同的路由参数。

<button (click)="onReload()">Search</button>

onReload() {
this.router.navigate(['results',this.location]);
}

这是我的ResultsComponent的路径路径

{ path:'results/:location', component:ResultsComponent}

此功能更改URL,但不会重新初始化组件。

在angularjs中,ui-router我可以像这样实现它。

$state.go($state.current, location, {reload: true});

我如何在angular4中执行此操作?

3 个答案:

答案 0 :(得分:4)

您需要在route.params可观察流的订阅回调函数中的订阅回调函数中执行初始化逻辑。

在您的组件类

@Component({
  ...
})
export class MyComponent implements OnInit {

   myLocation:string;

   constructor(private route:ActivatedRoute) {}

   ngOnInit() {
     this.route.params.subscribe((params:Params) => {
        this.myLocation = params['location'];
        // -- Initialization code -- 
        this.doMyCustomInitialization();
     }
   }

   private doMyCustomInitialization() {
       console.log(`Reinitializing with new location value ${this.location}`);
   }
}

另一方面,如果您需要根据“位置”的值解析数据,则应使用解析保护,该解决保护在创建组件之前解析数据。有关解决方案和路由的详细信息,请参阅https://angular.io/guide/router#resolve-guard

这是一个有效的傻瓜。 https://plnkr.co/edit/g2tCnJ?p=preview

答案 1 :(得分:2)

https://angular-2-training-book.rangle.io/handout/routing/routeparams.html

在您的组件中,您需要订阅参数以检测它们是否已更改。

答案 2 :(得分:2)

EDITED

告诉路由器执行此操作的角度方式是从角度5.1

开始使用onSameUrlNavigation

但我必须以不同的方式解决此问题(Stackblitz),subscribingroute events并实际调用custom reInit method

诀窍是将所有订阅添加到同一个对象,然后仅在角度调用ngOnDestroy时取消订阅,并且从custom destroy method ...

    public subscribers: any = {};

    constructor(private router: Router) {
    /** 
      * This is important: Since this screen can be accessed from two menu options 
      * we need to tell angular to reload the component when this happens.
      * It is important to filter the router events since router will emit many events,
      * therefore calling reInitComponent many times wich we do not want.
      */   
      this.subscribers._router_subscription = this.router.events.filter(evt => evt instanceof NavigationEnd).subscribe((value) => { 
        this.reInitComponent();
      });
    }

    reInitComponent() {
        this.customOnDestroy();
        this.customOnInit();
    }

    customOnInit() {
        // add your subscriptions to subscribers.WHATEVERSUB here
        // put your ngOnInit code here, and remove implementation and import 
    }

    customOnDestroy() {
      // here goes all logic to re initialize || modify the component vars  
    }

    /**
     * onDestroy will be called when router changes component, but not when changin parameters ;)
     * it is importatn to unsubscribe here
     */
     ngOnDestroy() {  
       for (let subscriberKey in this.subscribers) {
          let subscriber = this.subscribers[subscriberKey];
          if (subscriber instanceof Subscription) {
            subscriber.unsubscribe();
          }
        }
     }

请注意,如果您实现了lifecylce hook ngOnInit,则应将其删除并实现自定义方法,如示例所示。

由于this角度错误,我添加了unsubscription方法。在销毁组件时,Angular实际上应该自动取消订阅router.events,但由于情况并非如此,如果您不手动取消订阅,您最终会在输入组件时多次调用http请求(例如)。