简体   繁体   English

JavaScript / TypeScript / Angular4中的对象URL映射

[英]Object URL mapping in JavaScript / TypeScript / Angular4

I have a class for SearchFilter 我有一个SearchFilter

class SearchFilter { 
   constructor(bucket: string,
               pin: number,
               qty: number,
               category: string) {
   }
}

When user hits search I'm filling in the filter to matrix params. 当用户点击搜索时,我会在过滤器中填写矩阵参数。

router.navigate(['filter', searchFilter]); //searchFilter is an instance

The URL looks like 网址看起来像

filter;bucket=MPC123;category=JOINT;qty=90;pin=9087

This is being used in another component where the param is mapped back to an Object of type SearchFilter . 在另一个将参数映射回到SearchFilter类型的Object的组件中使用了此方法。 But here the data types need to be set explicitly as far as I know. 但是据我所知,这里需要显式设置数据类型。

   const params = this.activatedRoute.snapshot.params;
   const filter = this.getFilterFromParams(params);

   getFilterFromParams(params) :SearchFilter {
      const filter = new SearchFilter();
      Object.keys(params).forEach((key) => {
         switch(key) {
             case 'pin':
             case 'qty': filter[key] = Number(params[key]); break;
             default: filter[key] = params[key];
         }
      });
      return filter;
   }

As seen from above code, to map the params back to Object a custom mapping function is written, the question is if there is any other obvious way this can be done or is this a common pattern? 从上面的代码可以看出,要将参数映射回Object,需要编写一个自定义的映射函数, 问题是是否可以通过其他任何明显的方式完成此操作,或者这是常见的模式吗?

I will have to depend on URL as users should be able to share URLs of different filters. 我将不得不依赖URL,因为用户应该能够共享不同过滤器的URL。

You could maybe go for the capabilities of Object.assign and the spread syntax: 您也许可以使用Object.assign的功能和传播语法:

getFilterFromParams(params) :SearchFilter {
    return Object.assign(new SearchFilter(), params,
        ...['pin', 'qty'].map(key => key in params && { [key]: Number(params[key]) })
    );
}

Adding a static factory method would work: 添加静态工厂方法将起作用:

class SearchFilter { 
  constructor(
    bucket: string,
    pin: number,
    qty: number,
    category: string) {
  }

  public static fromParams({ bucket, pin, qty, category }) {
    // TODO Add validation to ensure pin & qty are integers
    return new SearchFilter(
      bucket,
      parseInt(pin),
      parseInt(qty),
      category);
  }
}

Then we can use it like this: 然后我们可以像这样使用它:

const demoParams = {
  bucket: "MPC123",
  category: "JOINT",
  qty: "90",
  pin: "9087"
};

const filter = SearchFilter.fromParams(demoParams);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM