【问题标题】:How to Update queryParams in URL without reload page in angular 6如何在 Angular 6 中更新 URL 中的 queryParams 而无需重新加载页面
【发布时间】:2018-08-17 09:34:38
【问题描述】:

我有 Angular6 项目。它具有列表组件和详细信息组件。在列表组件中,我有一个搜索框。当我搜索任何内容并基于此重定向到详细信息页面时,我正在分配 queryParams,而当我返回时,我将保留这些 queryParams。它工作正常。

但是,当我在搜索框中键入任何内容时,我想使用在搜索框中输入的更新后的搜索字符串来更新 URL,而无需再次重新加载页面,即...我想保持 queryParams 的更新,同时更改搜索框输入字段。

listing.component.html

<div class="input-group">
    <input type="text" name="search" [(ngModel)]="search">
</div>
<div class="row" *ngFor="let List of Lists | searchFilter:search:'name' | paginate: { itemsPerPage: 25, currentPage: page }">
    <div (click)="editList(List.ListId)">{{List.name}}</div>  
</div>

listing.component.ts

ngOnInit(): void {
    this.search = this.activatedRoute.snapshot.queryParams['search'] || '';
}

editPrice(ListId: number): void {
    this.router.navigate(['lists/edit', ListId], { queryParams:
        { search: this.search }
    });
}

detail.component.html

<a [routerLink]="['/lists']" queryParamsHandling="preserve">Go Back</a>

【问题讨论】:

标签: angular angular-ui-router angular6


【解决方案1】:

假设您想用anotherId 更新参数id

import { Location } from '@angular/common';

constructor(
    private route: ActivatedRoute,
    private location: Location,

) { }


ngOnInit() {
        this.route.paramMap.subscribe(param => {
            this.id = param.get('id');
        });
  }


updateUrl(){

   let anotherId : number = '10'

   let cururl = this.location.path().replace(this.id, anotherId );

   this.location.go(cururl);
}

【讨论】:

  • 在我的例子中,我的搜索变量绑定了 HTML 搜索框...那么我应该如何替换搜索变量 => this.location.path().replace(this.id, anotherId);
【解决方案2】:

订阅activatedRoute.params,而不是activateRoute.snapshot

例如:

 this.activateRoute.params.subscribe((data) => {
     this.search = data.search
     // Your search logic here
 });

【讨论】:

  • 在这个你需要再次调用你的函数搜索,它具有搜索@ErVipinSharma的逻辑
猜你喜欢
  • 2016-01-12
  • 1970-01-01
  • 2016-02-01
  • 2019-07-10
  • 1970-01-01
  • 2019-09-24
  • 1970-01-01
  • 2013-04-25
  • 2019-01-28
相关资源
最近更新 更多