如何在不破坏组件angular5的情况下更改url [英] how to change the url without destroying the component angular5

查看:34
本文介绍了如何在不破坏组件angular5的情况下更改url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于Angular2世界来说只是一个新手,但是通过指定{reload:false},它在angular 1中非常简单,但是无法在Angular 2中找到类似的解决方案,在Angular 2中我可以避免在更改查询参数的同时重新加载组件我的路线.

Just a little new to Angular2 world, however it was preety simpler in angular 1 by specifying {reload: false} but not able to find a similar solution in Angular 2 where I can avoid reloading the component while changing the query param in my route.

我有html模板,单击按钮即可更改查询参数.

I have html template, where I am changing the query parameter on click of a button.

我有方法updateRoute({type:'app_dependency'}),只需单击按钮即可调用:

I have the method updateRoute({type: 'app_dependency'}) which gets called on click of the button:

  ngOnInit() {
    console.log(`ngOnInit  - is called. `);
  }
  public updateRoute(urlObject){
    let queryParams = this.activatedRoute.snapshot.queryParams;
    let updatedQuery = clone(queryParams);
    this.activeTab = updatedQuery.type || 'app_dependency';
    forEach(urlObject, (value, key) => {
      updatedQuery[key] = value;
    });
    //this.location.search({type: 'app_dependency'})
    this.router.navigate([], {
      relativeTo: this.activatedRoute,
      queryParams: queryParams
    });
  }

但是每次调用此函数时,它都会破坏该组件并调用ngOnInit().

But every time this function gets called, it destroys the component and calls ngOnInit().

是否可以仅更改url查询(我不更改路线,而是更改查询)而无需重新加载组件?如果是,请问有人可以帮我还是建议我一种更好的方法.

Is it possible to just change the url query (I am not changing the route but just changing the query) without reloading my component? If yes, can anyone please help me or suggest me a better approach.

推荐答案

我在这里找到了解决方案:
这样可以防止组件被破坏.

I have found a solution here:
It will prevent the component from being destroyed.

constructor(
        private router: Router
      ) {
        this.router.routeReuseStrategy.shouldReuseRoute = function () {
          return true;
        };
      }

这篇关于如何在不破坏组件angular5的情况下更改url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆