我有一个显示 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/