Ad

Getting Typescript Error In Angular , Not Able To Bind This Properly

- 1 answer

const stateObj = {
        indicators: stateIndicators,
        filters: stateFilters,
        benchmarks: stateBenchmarks,
        request: stateRequest,
        ready: stateReady,
        visualization: stateVisualization,
        dimensions: stateDimensions,
        datasets: stateDatasets
      };

extend({
        getDefaultIndicators: function () {
          return stateObj.indicators.enabledIndicators
            .map((indicator) => find(stateObj.indicators.indicators, { name: indicator }));
        },
        getEnabledIndicators: function () {
          return this.request.indicators
            .map((i) => find(stateObj.indicators.indicators, { name: i }));
        },
        getEnabledBenchmarks: function () {
          return filter(stateObj.benchmarks, 'selected');
        },
        save: function () {
          if (tile) { return; }
          let serializedState = this.serialize();
          this.userStorage.saveExploreState(entity, serializedState);
        },
        serialize: function () {
          return {
            request: this.request,
            benchmarks: map(this.getEnabledBenchmarks(), 'name'),
            visualization: this.visualization,
            dimensions: this.dimensions,
            datasetId: datasetId
          };
        }
      }, stateObj);

Property 'request' does not exist on type '{ getDefaultIndicators: () => (Indicator | undefined)[]; getEnabledIndicators: () => any; getEnabledBenchmarks: () => { selected: boolean; name: string; }[]; save: () => void; serialize: () => any; }

Extend is lodash function I am getting type error for 'this.dimensions', 'this.visualization' as 'this' is not binding with stateObj and also 'this.userStorage' is class property , How to fix this issue.

Ad

Answer

Use arrow function to bind this context.

Try this:

extend({
        getDefaultIndicators: () => {
          return stateObj.indicators.enabledIndicators
            .map((indicator) => find(stateObj.indicators.indicators, { name: indicator }));
        },
        getEnabledIndicators:  () => {
          return this.request.indicators
            .map((i) => find(stateObj.indicators.indicators, { name: i }));
        },
        getEnabledBenchmarks: ()=> {
          return filter(stateObj.benchmarks, 'selected');
        },
        save:() => {
          if (tile) { return; }
          let serializedState = this.serialize();
          this.userStorage.saveExploreState(entity, serializedState);
        },
        serialize: ()=> {
          return {
            request: this.request,
            benchmarks: map(this.getEnabledBenchmarks(), 'name'),
            visualization: this.visualization,
            dimensions: this.dimensions,
            datasetId: datasetId
          };
        }
      }, stateObj);
Ad
source: stackoverflow.com
Ad