Skip to content Skip to sidebar Skip to footer

Object Url Mapping In Javascript / Typescript / Angular4

I have a class for SearchFilter class SearchFilter { constructor(bucket: string, pin: number, qty: number, category: string) { }

Solution 1:

Adding a static factory method would work:

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

  publicstaticfromParams({ bucket, pin, qty, category }) {
    // TODO Add validation to ensure pin & qty are integersreturnnewSearchFilter(
      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);

Solution 2:

You could maybe go for the capabilities of Object.assign and the spread syntax:

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

Post a Comment for "Object Url Mapping In Javascript / Typescript / Angular4"