URL 更改未在 Angular 中触发

URL Change not firing in Angular

所以我的 Angular 应用程序有一个搜索栏,如果您在此搜索栏中输入内容,它会进行搜索并进入结果页面。一切都很好。

现在,如果您的搜索 return 没有任何结果,结果页面会加载并告诉您 "searchterm" return 没有结果。此时,URL为localhost:4200/searchResults;query=searchterm。再次 - 一切都如预期。

现在,如果您转到搜索栏并输入不同的搜索词,则什么也不会发生...

嗯,那是不正确的...URL 现在说 localhost:4200/searchResults;query=NEWsearchterm,但是因为我们在 'same' 应用程序页面上,ngOnInit 不会重新启动(因此实际上搜索对于术语)也不会触发 ngOnChanges(因此实际上是在搜索术语)...

路由模块似乎做了它应该做的事情,因为我们的 URL 确实更改为引用新的搜索词,但是应该发生的事情没有发生,我不知道是什么?

这是我在路由模块中遗漏的问题吗(尽管我不这么认为,因为 URL 确实发生了变化),或者我在组件 [=29= 中遗漏了什么] 在应用页面上???

尝试订阅路线变更

class MyClass {
  constructor(private router: Router) {
    router.events.subscribe((val) => {
      if(val instanceof NavigationEnd){
        console.log("refreshing");
      }
    });
  }
}

从 angular 5.1 开始,告诉路由器这样做的 angular 方法是使用 onSameUrlNavigation...但是我认为实现这个仍然有一些麻烦。

所以我不得不以不同的方式解决这个问题 (Stackblitz),从 subscribingroute events 并实际调用 custom reInit method

诀窍是将所有订阅添加到同一个对象,然后仅在 angular 调用 ngOnDestroy 时取消订阅,然后将模板变量的其余部分从 custom destroy method ...如果您没有任何订阅并且没有实现 ngOnInit lifcycle ehook,那么@Yazan Mehrez 的答案应该可以,但是如果您有订阅或使用钩子,那么您需要像下面这样的实现来防止内存泄漏:

    public subscribers: any = {};

    constructor(private router: Router) {
    /** 
      * This is important: Since this screen can be accessed from two menu options or has query string parameter changes  
      * 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 挂钩 ngOnInit,则应将其删除并像示例中一样实现自定义方法。

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