查询参数更改时,Angular 路由器导航不会加载页面

标签 angular angular-routing

我有一个显示 API 查询结果的组件。我想添加一个下拉框,以便可以过滤列表,但是当 url 查询参数更改时,我似乎无法重新加载页面。

<div>
  <H2>Products</H2>
  <form>
    Filter By Manufacturer
    <select (change)="onManufacturerChange($event.target.value)">
      <option value="">All</option>
      <option [value]="m" *ngFor="let m of manufacturers">{{m}}</option>
    </select>
  </form>
  <ul>
    <li *ngFor="let p of products"><B>{{p.manufacturer}}</B> - {{p.name}}</li>
  </ul>
</div>

和 typescript
export class ProductListComponent implements OnInit {

  public products: Array<object> = [];
  public manufacturers: any = [];
  public manufacturer: string = "";
  public search: string = "";

  constructor(private _assetService: AssetService, private router: Router, private route: ActivatedRoute) { }

  ngOnInit() {
    this.route.queryParams.subscribe(params => {
      console.log(params);
      if('manufacturer' in params){
        this.manufacturer = params.manufacturer;
      }
      if('search' in params){
        this.search = params.search;
      }
    })

    this._assetService.getManufacturers().subscribe(data => {
      this.manufacturers = data;
    })

    this.loadProducts(); 
  }

  loadProducts(){
      this._assetService.getProducts(this.manufacturer,this.search).subscribe((data: ProductListResult) => {
      this.products = data.products;
    }) 
  }

  onManufacturerChange(newValue){
    this.router.navigate(['/products'], {queryParams: {manufacturer: newValue}});
  }
}

当我更改下拉框中选择的项目时,浏览器中显示的 URL 会更改,但页面不会重新加载。如果我使用所需的 URL 手动刷新浏览器,则会显示正确的输出。如果我将 route.navigate 中的路径更改为完全不同的可以正常工作的路径。如果我添加到 loadProducts() 的电话路由器导航一些后,它重新加载页面,但一个选择异相。

我读过的所有内容都说,如果 ngFor 中引用的数组发生更改,它应该自动更新 DOM,但我似乎无法触发它。我是否需要调用某种刷新或无效例程来更新 DOM?我需要在路由器中设置一些东西来识别查询参数的变化吗?我在这一切都错了吗?

最佳答案

截至 Angular v5 Router 现在有一个选项类(class)onSameUrlNavigation

How to handle a navigation request to the current URL. One of:

  • 'ignore' : The router ignores the request.

  • 'reload' : The router reloads the URL. Use to implement a "refresh" feature.


在主应用程序路由文件中,将值设置为 'reload' :
RouterModule.forRoot(
  routes,
  { onSameUrlNavigation: 'reload' }
)

关于查询参数更改时,Angular 路由器导航不会加载页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55139855/

相关文章:

angular - Mat-Table(数据源)+ 使用 Ngrx Store/Effects

javascript - 如何在 Angular2 应用程序中使用 ngrx-effects 从商店返回分页数据或从 api 服务返回新数据?

namespaces - 角达特 : Namespace of route names hierarchical too?

Angular 7 - 使用 queryParams 定义路由

angular - 不确定如何在 Angular 组件中使用自定义 TypeScript 类

sql-server - 似乎无法让我的.Net Core应用程序在Docker容器中与SQL Server一起使用

javascript - 我需要将文本框名称传递到 AngularS 路由页面吗?

angular - 错误 : Can't resolve all parameters for HomeComponent: (?)

javascript - 如何在 angularJS 中为一个 View 定义多个 Controller ?

json - Angular 6 - JSON 中位置 0 的意外标记