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

Rob*_*ave 5 angular-routing angular

我有一个显示 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>
Run Code Online (Sandbox Code Playgroud)

和打字稿

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}});
  }
}
Run Code Online (Sandbox Code Playgroud)

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

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

Rob*_*ave 0

据我所知,当查询参数发生变化时,没有一种优雅的方法可以让 Angular 重新加载页面。

我的代码中的错误是loadProducts()使用 this.manufacturer 所以我需要在onManufacturerChange()中设置它。它不会重新加载页面,但会重新加载数据并更新 DOM。

然后我需要创建一个updateRoute()函数,该函数在 subscribe 从 api 加载数据后调用。浏览器中的后退和前进按钮仍然不起作用(它会逐步浏览 URL,但不会更新显示),但 URL 和显示会保持同步。现在已经足够接近了。

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

  onManufacturerChange(newValue){
    this.manufacturer = newValue;
    this.loadProducts();
  }

  updateRoute( ){
    var queryParams = {};
    if (this.manufacturer!= "" ){queryParams['manufacturer'] = this.manufacturer;}
    if (this.search!= "" ){queryParams['manufacturer'] = this.search;}
    this.router.navigate(['/products'], {queryParams: queryParams});
  }
Run Code Online (Sandbox Code Playgroud)