Typescript:从查询字符串填充表格过滤器值(异步调用的最佳方法)

时间:2018-12-21 17:00:16

标签: angular typescript

我使用打字稿(用于角度书写)。 我有带过滤器的表格(下拉列表)。向后端请求每个过滤器的数据,并且所有调用都是异步的。所以首先我需要为所有过滤器加载数据。同时,我需要为从查询字符串中获取这些值的过滤器设置默认值。因此,我必须订阅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。我相信这是错误的。

1 个答案:

答案 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; 
      });