Angular Typescript:从查询字符串填充表筛选器值(异步调用的最佳方法)
我使用打字脚本(用于角度)。 我有带过滤器的表(下拉列表)。每个筛选器的数据都是从后端请求的,所有调用都是异步的。所以首先我需要加载所有过滤器的数据。同时,我需要为从查询字符串中获取这些值的过滤器设置默认值。因此,我必须订阅Angular Typescript:从查询字符串填充表筛选器值(异步调用的最佳方法),angular,typescript,Angular,Typescript,我使用打字脚本(用于角度)。 我有带过滤器的表(下拉列表)。每个筛选器的数据都是从后端请求的,所有调用都是异步的。所以首先我需要加载所有过滤器的数据。同时,我需要为从查询字符串中获取这些值的过滤器设置默认值。因此,我必须订阅route.queryParams 由于异步调用、订阅和类似的原因,我无法以正确的方式执行此操作。遗憾的是,我还不太熟悉打字脚本 这是我的密码: ngOnInit(): void { this._service.getTypes() // get types - da
route.queryParams
由于异步调用、订阅和类似的原因,我无法以正确的方式执行此操作。遗憾的是,我还不太熟悉打字脚本
这是我的密码:
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。我认为这是错误的。作为
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;
});
有趣的问题,我不知道你会怎么做。我所能想到的可能就是使用Observable.forkJoin
Observable.forkJoin(this.\u service.getClients().map(res=>{this.types=result.items;})this.\u service.getTypes().map(res=>{this.types=result.items;})).subscribe(res=>{…一起设置默认值…})代码>如果您添加标记rxjs,您可能会得到一些更好的答案。