Exploring Angular's capabilities with filtering and handling $http promises

Having an issue with filtering data from a JSON file that contains an array of 20 objects.

Within my factory, I have implemented two functions:

function fetchData() {
    return $http
        .get('mock.json')
        .success(_handleData)
        .error(_handleError);
}

function _handleData(data) {
    var filteredData = _filterByProperty(data, "name", "XYZ");

    console.log('filteredData', filteredData);

    return filteredData;
}

When I check the console.log("filteredData"), it only displays the filtered elements (3 out of 20);

In a service, there is an ng-click function which does the following:

var applyFilter = function () {
    DataFactory
        .fetchData(_address)
        .success(_handleServiceData);
}

where

var _handleServiceData = function (data) {
    filteredData = data;
};

The question arises - why does the 'data' in _handleServiceData display all the elements instead of the previously filtered ones?

edit: Link to the plunk for reference - results are visible in the console

Answer №1

The issue stems from the fact that the filteredData returned by the _handleData function is not being passed to the success callback within the filterMe function. This is because the callback is attached to the same promise, unlike the then method which creates a new promise. To resolve this, update your code as follows:

function getData() {
    return $http
       .get('mock.json')
       .then(_handleData, _handleError); //replace "success" with "then"
}

Then, in the filterMe function:

var filterMe = function () {
    DataFactory
        .getData(_address)
        .then(_handleServiceData);
}

Answer №2

Due to the asynchronous nature of promises, it appears that you are returning the value of filtered to your caller before it has been assigned.

It is recommended to modify your code as follows:

function retrieveData() {
    return $http
        .get('mock.json')
        .then(_handleData); // utilizing then (for chaining), not success!
}
var filterData = function () {
    return DataFactory
//  ^^^^^^ ensure to return a promise, refrain from assigning globals within asynchronous callbacks
        .retrieveData(_address)
        .catch(_handleError); // the assumption is error handling should occur at the end
}

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

Maintaining sequential order IDs for table rows even after removing records

I currently have a table structured as follows: <table> <tr> <td> <input type="hidden" name="help[0].id" /> </td> <td> <span class="tr-close">X</span> </tr> <tr ...

Tips for sending a string from the state of a React component to an external Python script

My journey into ReactJS and web development is just beginning. I am currently working on a web application where users can input mathematical expressions as strings. Upon submitting the input, I intend to process it using a Python script and display the o ...

Leverage the power of an Express server to manage a Node.js application

I have a node.js application that communicates with a REST API hosted on a separate server. To control this application, I want to create a web interface using express.js which includes HTML, CSS, and Javascript. How can I enable the browser to interact w ...

Having issues with the autocompletion feature in ng-tags-input

I am trying to integrate the ng-tags-input with Autocomplete functionality, but encountering an issue: e.then is not a function This is the code snippet from my HTML file: <tags-input ng-model="selectedBodyParts" class="ui-tags-input" add-on-paste= ...

Creating synchronous automation in Selenium: A step-by-step guide

I am feeling increasingly frustrated at the moment and I am hoping to seek assistance on stackexchange. First and foremost, I must admit that I am not a seasoned Javascript developer, probably not even an experienced developer overall, but I do have some ...

Tips for changing an angular variable string before sending it to a PHP function

When working with AngularJS, I can access form variables within my function like this (for example: s1 = Joe Smith). However, I have a need to update the Indata variable by replacing the a_searchvalue1 with the value stored in s1 but wrapped in quotes. O ...

To properly format the date value from the ngModel in Angular before sending it to the payload, I require the date to be in the format

When working with Angular 9, I am facing an issue where I need to format and send my date in a specific way within the payload. Currently, the code is sending the date in this format: otgStartDate: 2021-07-20T09:56:39.000Z, but I actually want it to be for ...

Incorporating an external JSX file into an HTML page in a React project

I have a React code in my js/script.js file. My HTML page's head tag is structured like this: <head> <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="06746367657246373328302834" ...

JavaScript: void(0), Internet Explorer 6, and SWFAddress are all important components

Hello there, We are on the verge of launching a secure website (regrettably, we cannot provide the URL) and have come across a rather obscure bug in IE6 that I am hoping someone may have experienced or could shed some light on. This issue only arises when ...

Enhance the display in Angular2

Just started working with Angular 2 and I've encountered a problem. I have an API that loads a JavaScript file in my project. The issue is, I need to use this JS file and cannot modify it. Essentially, this JS file has some methods that make AJAX call ...

Only the first element can trigger reactions in jQuery and Ajax!

I am facing an issue on this particular page where I have several forms that can be optionally submitted using ajax. The problem lies in the fact that only the first element selected by jQuery is getting executed! Below is the JavaScript code: $(function ...

Issue with Slider Width in WP 5.6 editor and ACF Pro causing layout problems

Is anyone else experiencing a specific issue after updating to WP 5.6? Since the update, all my websites are facing problems with rendering a Slick Slider in the Block Editor. Interestingly, everything looks fine on the front-end. The root of the problem ...

Leverage the power of both ui-sref and $state.go for seamless state transitions in Angular's ui

Currently, I am in the process of constructing a sign-up form that will collect user input and then transition to a logged-in state with a template tailored specifically for this new user. To achieve this, my understanding is that I need to utilize ng-sub ...

Obtaining JSON data in a separate JavaScript file using PHP

I have an HTML file with the following content: // target.html <html xmlns="http://www.w3.org/1999/xhtml"> ... <script src="../../Common/js/jquery-ui-1.10.3.js"></script> <script src="../../Common/js/select.js" type="text/javascript"& ...

"What is the best way to access the value of a useState variable in ReactJS on a global

Below is my reactJS code snippet - useEffect(()=>{ const getinterviewerDetails= async ()=>{ const data1 = await axios.get("http://localhost:8083/api/GetProduct") .then(response => { console.log("role is " ...

The ReCaptcha and AJAX Integration

I am attempting to display the ReCaptcha image using its AJAX API. I have been following the instructions from this documentation and observing the behavior of this demo. Despite my efforts, I am still unable to create a functional fiddle. I have added jsf ...

Loading Collada files with a progress callback function can help track the

Is there a proper way to incorporate a loading bar while using the ColladaLoader? The code indicates that the loader requires three parameters, with one being a progressCallback. progressCallback( { total: length, loaded: request.responseText.length } ); ...

Navigating through a Single Page Application (SPA) can be achieved without

Can the CSS (Level 4) @document rule handle URLs that have the # symbol or include query parameters? For those who are not familiar with this topic Currently, only Firefox supports this feature with the @-moz-document prefix. If other browsers start supp ...

Implement a callback function for unchecked checkboxes on change

Currently, I am working with a gridview that includes a checkbox field. My goal is to use jQuery to create a function that activates when an unchecked checkbox is checked. function clickAllSize() { alert("helloy"); } $(document).ready(function () { ...

Reactjs - Creating a video component with a placeholder that loads the video seamlessly

I created a Video component that utilizes the React.Suspense component to show a placeholder while the video is loading. However, I'm facing an issue where it seems like the functionality isn't working as intended. When I set the network to "slow ...