Issues Arising from Abstraction of Function to Service Layer in Angular Application

I have a filter function that takes in user filter selections and returns data accordingly. Currently, I am using this function in multiple components to avoid repetition (DRY). To streamline the process, I decided to refactor it into a service layer. However, after moving part of the function into the service layer, the data is not being filtered as expected.

Initially, here is the existing component function that is functioning correctly:

public onFilterReceived(value, type, page) {
    if (value && type === 'lan') {
        this.language = value;
    }
    else if (value && type === 'location') {
        this.location = value;
    }
    // Remaining conditional logic...
}

// Rest of the code remains the same

After getting the above working, I attempted to separate the initial part of the function responsible for handling conditional logic into a service layer. This resulted in the following service layer implementation:

public processByTypes(value, type) {
    let language, location, zipcode, firstName, lastName, branch;

    if (value && type === 'lan') {
        console.log(value);
        language = value;
    }
    else if (value && type === 'location') {
        location = value;
    }
    // Remaining conditional logic...
}

Subsequently, I updated the component as follows:

public onFilterReceived(value, type, page) {

    this.filtersService.processByTypes(value, type);

    // Remaining logic...
}

However, this modification is not yielding the expected results.

I verified that the filter selections are reaching the service layer since the "language" console.log successfully displays the user's selection value. Nonetheless, this value is not returned to the component layer for filtering the data appropriately. What crucial detail might be missing from this approach? It could be something glaringly obvious, but perhaps due to prolonged examination, it eludes me.

Answer №1

The variables within the function filtersService.processByTypes are only available locally and lose their meaning once the function ends unless you explicitly return them.

To return the values from the function, you can structure it like this:

public processByTypes(value, type) {
    let language, location, zipcode, firstName, lastName, branch;

    if (value && type === 'lan') {
        console.log(value);
        language = value;
    }
    else if (value && type === 'location') {
        location = value;
    }
    else if (value && type === 'zip') {
        zipcode = value;
    }
    else if (value && type === 'firstName') {
        firstName = value;
    }
    else if (value && type === 'lastName') {
        lastName = value;
    }
    else if (value && type === 'branch') {
        branch = value;
    }
    return {language:language, location:location, zipcode:zipcode, firstName:firstName, lastName:lastName, branch:branch};
}

Then, in the component, you can utilize these returned values like so:

public onFilterReceived(value, type, page) {

    let selections = this.filtersService.processByTypes(value, type);

    let fn = resRecordsData => {
        this.records = resRecordsData;
        let data = resRecordsData.data;
    };

    this.filtersService.getByFilters(
        page, this.pagesize, selections.language, selections.location, selections.zipcode, selections.firstName, selections.lastName, selections.branch, fn);
}

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

Tabulate the number of items in an array based on the month and

I have received JSON data with dates indicating the creation time of multiple parcels. I want to analyze this data and calculate the total number of parcels created in each month. I am new to this process and unsure about which thread on Stack Overflow can ...

What methods can be used for child components to communicate in React and React-Native?

Is there a way for child components in React to directly call functions from one another, such as accessing test1() from test2() or vice versa? I already have access to both functions from the parent components through ref_to_test1 and ref_to_test2. But ...

Tips for accessing payment details from a stripe paymentElement component in a React application

Here is a basic code snippet for setting up recurring payments in Stripe: await stripe ?.confirmSetup({ elements, confirmParams: { return_url: url, }, }) After browsing through the documentation and the internet, I have two unanswere ...

Streaming audio live using HTML5 and NodeJS technology

I'm currently working on developing a website that functions as a VoIP recording application. The main goal is to capture audio from the microphone, send it exclusively to the server for storage and then have the server distribute the audio to connect ...

Using jQuery to iterate through elements of a PHP array

I've got a PHP array that outputs like this: Array ( [0] => Array ( [title] => Much title [end] => Such end [start] => Very start ) [1] => Array ( [title] ...

Is there a way to determine if the validityMessage is currently being displayed on a DOM element using reportValidity()?

When reportValidity() is called on an invalid field, the validation message is displayed in a manner that varies depending on the browser. However, if reportValidity() is called again, the validation message disappears on Safari but not on Firefox. Contin ...

Tips for handling numerous requests using Express.JS

I am currently working on an Angular 6 + Express.JS application and have encountered a problem. When multiple requests are made simultaneously, especially when there are more than 4 requests, all of them sometimes respond with a 404 error or get cancelled. ...

Creating a unique navigation route in React

My application has a consistent layout for all routes except one, which will be completely different from the rest. The entire application will include a menu, body, footer, etc. However, the one-off route should be standalone without these elements. How ...

What is the process of creating a mongoDB schema object in JavaScript when dealing with dynamically changing keys in a JSON?

I need to design a schema in mongoDB for an AngularJS project, but the json keys are dynamic. The structure of the json is as follows: { “1” : { “Name” : “John”, “City” : “London” }, “2” : { ...

What is the hierarchy of importance for routes in Angular - parent versus child levels?

Let's say I define a top-level route with the path '/some/childr': [{ path: '/some/childr'}] Then, I create another top-level route /some with a child route /childr: [{ path: '/some', children: ['/childr']}] ...

The jQuery click and load function are failing to function as expected

Currently, I am facing an issue while trying to load text from a txt document into a div using the following code: $(document).ready(function(){ $('button').click(function(){ $('#contenthere').load('Load.txt'); ...

Ensuring the continuous transmission of data frames is essential for WebSocket communication

Our system utilizes websocket technology to transmit user activity events such as clicks, mouse movement, scroll, input, and more. In addition to these events, we also send a snapshot of the HTML DOM. On average, the size of the HTML snapshot is approximat ...

In Node.js and Express, it is important to note that a variable must be declared before

When I use the express action get('items'), I encounter an issue while trying to call an external JSON-API and display the API response in my local response. The error that I am currently facing states that the items variable is not defined with ...

Ensuring the script waits for the complete loading of iframe prior to

I'm faced with an issue on the website I'm currently working on. There's a Live Chat plugin integrated on an iframe, and I need to change an image if no agents are available. Interestingly, my code works perfectly fine when tested on the con ...

Exceljs : 'An issue has been identified with certain content in the document named "file.xlsx"(...)'

I have encountered an issue with an xlsx file generated using Exceljs. While I have been creating csv files in my project without any problems, creating an xlsx file now poses an error. The xlsx file opens clean on Ubuntu/LibreOffice Calc, but there is an ...

What is the best way to ensure all asynchronous tasks are completed in Node.js before proceeding?

My program is in need of running numerous asynchronous tasks. Additionally, there needs to be a task that will only run once all the other asynchronous tasks have completed. Is there a way I can create a function that waits for all async functions to fin ...

Searching within a container using jQuery's `find` method can sometimes cause jQuery to lose control

I am trying to extract information from an input field within a table in a specific row. Here is the code I am using: var myElements = $('#myTable tbody').find('tr'); console.log(myElements); This correctly displays the items in the ...

Tips on instructing TypeScript to view a parameter as a namespace instead of a class, especially when they share the same name - gRPC

Apologies for the lengthy title... I am in the process of developing a basic crud system using gRPC and typescript. My issue lies in the fact that the auto-generated file creates a class and a type for each parameter in my protoFile. For example, the User ...

jQuery tab plugin does not open in a new browser tab when the 'ctrl' key is pressed

I have implemented the Jquery easy tab plugin on my webpage. When I perform a right-click on each tab and open it in a new browser tab, it displays correctly. However, if I press the ctrl key on the keyboard and click on a tab, it opens in the same browse ...

Is there a way to access the Angular router instance without the need for injection?

In my component, I typically handle routing like this: import { Router } from "@angular/router"; @Component({ ... }) export class UniqueComponent { constructor(private router: Router) { console.log(router.url); } } But what if I need a referenc ...