我使用打字稿(用于角度书写)。
我有带过滤器的表格(下拉列表)。向后端请求每个过滤器的数据,并且所有调用都是异步的。所以首先我需要为所有过滤器加载数据。同时,我需要为从查询字符串中获取这些值的过滤器设置默认值。因此,我必须订阅route.queryParams
。
由于异步调用,订阅等原因,我无法以正确的方式执行此操作。不幸的是,我还不太熟悉Typescript。
这是我的代码:
ngOnInit(): void {
this._service.getTypes() // get types - data for filter1
.subscribe((result) => {
this.types = result.items;
this._route // subscribe to queryparams and set selected value for filter1
.queryParams
.subscribe(params => {
if (params['Type'] != undefined) {
this.selectedId = parseInt(params['LoadType']);
}
});
});
this._service.getClients() // get data for filter2
.subscribe((result) => {
this.clients = result.items;
this._route // set default value from query str for filter2
.queryParams
.subscribe(params => {
if (params['ClientCode'] != undefined) {
this.client = params['ClientCode'];
}
});
});
...
对于多个过滤器,依此类推,多次我订阅了queryParams。我相信这是错误的。
答案 0 :(得分:0)
由于route.queryParams
订阅不依赖于getTypes()
和getClients()
订阅结果,因此您可以分别编写它们,仅订阅一次route.queryParams
:
// subscribe to queryparams and set selected value for filter1 and filter2
this._route
.queryParams
.subscribe(params => {
if (params['Type'] != undefined) {
this.selectedId = parseInt(params['LoadType']);
}
if (params['ClientCode'] != undefined) {
this.client = params['ClientCode'];
}
});
this._service.getTypes() // get types - data for filter1
.subscribe((result) => {
this.types = result.items;
});
this._service.getClients() // get data for filter2
.subscribe((result) => {
this.clients = result.items;
});