Storing TypeScript functions as object properties within Angular 6

I am working on creating a simplified abstraction using Google charts. I have implemented a chartservice that will act as the abstraction layer, providing options and data-source while handling the rest (data retrieved from a REST API).

Below is the existing code snippet, which currently only caters to one specific case:

createCombo(comboBarLabels: String[], comboBarTypes: String[], options: any, element: any) {
    this.overviewService.getOverviewAggBarData().pipe(first()).subscribe(comboRequest => {
      for (const index of Object.keys(comboRequest.comboData)) {
        comboRequest.comboData[index].unshift(comboBarLabels[index]);
      }
      const data_array = [comboBarTypes, comboRequest.comboData[0],
        comboRequest.comboData[1], comboRequest.comboData[2]];
      google.charts.load('current', {'packages': ['corechart']});
      google.charts.setOnLoadCallback(() => {
        const data = ChartService.createDataTable(data_array);
        const chart = new google.visualization.ComboChart(element);
        chart.draw(data, options);
      });
    });
  }

My goal is to replace

this.overviewService.getOverviewAggBarData()
with a conditional function, somewhat like what can be done in Python:

def foo(a, b):  
    return a + b
a = foo
print(a(1, 2))  

Here is the desired pseudo-code:

createCombo(comboBarLabels: String[], comboBarTypes: String[], options: any, element: any, source: any) {
  if (source == "OverviewAggBar"){
    get_data = this.overviewService.getOverviewAggBarData;
  } else {
    get_data = this.overviewService.getOverviewPieData;
  }
  get_data().pipe(first()).subscribe(comboRequest => {
    for (const index of Object.keys(comboRequest.comboData)) {
      comboRequest.comboData[index].unshift(comboBarLabels[index]);
    }
    const data_array = [comboBarTypes, comboRequest.comboData[0],
      comboRequest.comboData[1], comboRequest.comboData[2]];
    google.charts.load('current', {'packages': ['corechart']});
    google.charts.setOnLoadCallback(() => {
      const data = ChartService.createDataTable(data_array);
      const chart = new google.visualization.ComboChart(element);
      chart.draw(data, options);
    });
  });
}

The objective behind this effort is to simplify the function call process. Abstracting this part away will enable us to create an even more versatile function. Any alternative solutions to achieve the same outcome are highly appreciated!

Issue resolved, presenting the updated code:

createCombo(comboBarLabels: String[], comboBarTypes: String[], options: any, element: any, source: string) {
    let getData: any;
    if (source === 'getAggData') {
      getData = this.overviewService.getOverviewAggBarData.bind(this);
    } else {
      getData = this.overviewService.getOverviewPieData.bind(this);
    }
    getData().pipe(first()).subscribe(comboRequest => {
      const data_array = [comboBarTypes];
      for (const index of Object.keys(comboRequest.comboData)) {
        comboRequest.comboData[index].unshift(comboBarLabels[index]);
        data_array.push(comboRequest.comboData[index]);
      }
      google.charts.load('current', {'packages': ['corechart']});
      google.charts.setOnLoadCallback(() => {
        const data = ChartService.createDataTable(data_array);
        const chart = new google.visualization.ComboChart(element);
        chart.draw(data, options);
      });
    });
  }

Answer №1

If you find yourself in a situation where you have numerous functions, consider establishing a "map" that connects the source string to each function. By doing so, you can easily incorporate additional functions into the map. Here's an example of how this could be implemented:

class YourClass {
    private mapFromSourceToFunction: { [key: string]: () => Observable<YourComboResponseType> } = {
        'getAggData': () => this.overviewService.getOverviewAggBarData(),
        'getPipeData': () => this.overviewService.getOverviewPieData(),
        'getSomethingElse': () => this.overviewService.getSomethingElse()
    };

    createCombo(comboBarLabels: String[], comboBarTypes: String[], options: any, element: any, source: string) {
        let getData = this.mapFromSourceToFunction[source];

        // getData().pipe ...
    }
}

Answer №2

It seems like you are on the right track already. JavaScript (and TypeScript) offers similar functionalities to achieve what you want. One area that needs improvement in your current code is the declaration of get_data variable. Here's how you can use a ternary operator for this purpose:

const get_data = source === "OverviewAggBar" ? this.overviewService.getOverviewAggBarData : this.overviewService.getOverviewPieData;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

`The resurgence of CERT_FindUserCertByUsage function in JavaScript`

I am currently grappling with unraveling the connection between C++ dlls and JavaScript. There is a snippet of js code that reads: cert = CERT_FindUserCertByUsage(certDB, certName.nickname,certUsageEmailSigner, true, null); where the variable cert is ini ...

Methods to Maintain Consistent HTML Table Dimensions utilizing DOM

I am facing an issue with shuffling a table that contains images. The table has 4 columns and 2 rows. To shuffle the table, I use the following code: function sortTable() { // Conveniently getting the parent table let table = document.getElementById("i ...

Create a new chart using completely unique information

I am currently working on implementing the example found at http://bl.ocks.org/mbostock/1093130. The goal is to have the "update" function redraw the graph with a completely different dataset each time a button on the DOM is pressed. I have made some modif ...

react-native-track-player failing to play song requested from Express server

I set up an expressjs server with a 'songs' route that serves .mp3 files. Here is the code for the Songs Route: import express from "express" const path = require("path") const router = express.Router() ... router.get(" ...

Error message: Missing "@nestjs/platform-express" package when performing end-to-end testing on NestJS using Fastify

Just set up a new NestJS application using Fastify. While attempting to run npm run test:e2e, I encountered the following error message: [Nest] 14894 - 11/19/2021, 10:29:10 PM [ExceptionHandler] The "@nestjs/platform-express" package is missi ...

Simulating a mobile device screen size using an embedded iframe

Imagine this scenario: What if instead of adjusting the browser window size to showcase a responsive web design, we could load the site into an IFRAME with the dimensions of a mobile screen. Could this concept actually work? Picture having an IFRAME like ...

Executing a function within a worker thread in Node.js

This is the worker I am using: const Worker = require('worker_threads'); const worker = new Worker("function hello () { console.log('hello world');}", { eval: true }) worker.hello() // this is incorrect I want to invoke the hello() fu ...

Gaining entry to a JSON object within an array

I've completed various courses on JSON and put in a lot of effort to troubleshoot this bug. However, it seems that my question is too specific and I require a practical example. JSON { "date": "2017-10-15", "league": "NHL", "odds": "spreads", ...

Implementing pagination using getServerSideProps in NextJS allows for dynamic

I'm currently using NextJS along with Supabase for my database needs. I'm facing a challenge with implementing pagination as the solution I'm seeking involves passing queries to the API. However, since I'm fetching data directly from th ...

An HTTP request is made with a JSON parameter to invoke a server-side GET function that does not

Having an issue with Angular's get method and unsure why the second server side function is being called instead of the first. Here is my code: var params = { "id": templateCategoryId }; this.http.get(this.appService.baseUrl + 'api/UserL ...

Issue with PrimeNG autocomplete dropdown. It only functions correctly upon initial use

Environment Info: NODE Version: 8.12.0 Angular Version: 7.3.4 PrimeNG Version : 7.0.0 I have integrated the dropdown feature of PrimeNG's autocomplete component into my application. The issue I am facing is that the dropdown only loads for the ...

Is it possible to retrieve data from Local Storage using user_id and SessionId, and if so, how can it be done?

I have some data in an interactive menu created with iSpring, which includes a feature for local storage to save the last viewed page. I also have a system for logging and need to associate this local storage with user_id or sessionid. I found some informa ...

What is the best way to assign an identifier to a variable in this scenario?

script.js $('a').click(function(){ var page = $(this).attr('href'); $("#content").load(page); return false; }); main.html <nav> <a href="home.html">Home</a> <a href="about.html">About</a> < ...

Mobile device scrolling glitch

I'm currently working on my website, which can be found at . After testing it on mobile devices, I came across an issue that I just can't seem to fix. For instance, when viewing the site on a device with 768px width, you can scroll to the righ ...

Issue with JQueryUI Dialog auto width not accounting for vertical scrollbar

My JQueryUI Dialog has the width property set to 'auto'. Everything functions properly except in situations where the content exceeds the height of the dialog: A vertical scrollbar appears, but it disrupts the layout of the content within the dia ...

Using jquery to loop through JSON objects based on their values

Looking to display the NBA Western Conference leaders by seed, I have utilized the JSON file available at: http://data.nba.com/data/v2014/json/mobile_teams/nba/2014/00_standings.json Here is the current setup: $(document).ready(function() { $.getJSON( ...

Utilizing jQuery for dynamic horizontal positioning of background images in CSS

Is there a way to set only the horizontal background property? I've tried using background-position-x and it works in Chrome, Safari, and IE, but not in Firefox or Opera. Additionally, I would like to dynamically set the left value of the position. ...

What causes TypeScript to convert a string literal union type to a string when it is assigned in an object literal?

I am a big fan of string literal union types in TypeScript. Recently, I encountered a situation where I expected the union type to be preserved. Let me illustrate with a simple example: let foo = false; const bar = foo ? 'foo' : 'bar' ...

Angular 2 and .NET Core 2.0 triggering an endless loop upon page refresh detection

My application, built with dotnet core 2.0 and angular 2, allows me to view member details. The process begins with a list page displaying all the members from a SQL Server database. Each member on the list has a link that leads to an individual details pa ...

Utilizing a combination of a `for` loop and `setInterval

I've been encountering an issue for the past 3-4 hours and have sought solutions in various places like here, here, here, etc... However, I am unable to get it to work in my specific case: var timer_slideshow = {}; var that, that_boss, has_auto, el ...