It appears that when filtering data in Angular from Web Api calls, there is a significant amount of data cleaning required

It appears that the current website utilizes asp.net web forms calling web api, but I am looking to convert it to Angular calling Web api. One thing I have noticed is that I need to clean up the data.

How should I approach this?
Should I use conditionals in the Html?

Here is an example of the old website output:

Device Status      Staged       Archived
-----------------------------------------
   Unactivated       None        002,003,001 
   New Device        None        None

This is how my Angular/html output looks like:

Device Status      Staged       Archived
-----------------------------------------
   3                null        [002,003,001] 
   1                null        []
  1. I need to assign meaningful Device Status to the numbers
  2. It seems like I always need to remove [] from the data

I am thinking about handling this in Javascript... as it might be better than doing it in Html with angular.

Any thoughts on this?

What would be the best practice for accomplishing this task, regardless of whether it's done in Javascript or Html?

Sample Data

{
 "Devices": [
  {
  "DeviceId": "00022B9A000000010001",
  "StagedManifestIdList": [],
  "PendingManifestId": null,
  "PendingTimeStamp": "0001-01-01T00:00:00",
  "ManifestIdList": [
    "00000002",
    "00000001",
    "00000003"
  ],
  "DeviceStatus": 3,
  "Aid": "oAAABTUAAg==",
  "DKiIndex": "DKi00000002",
  "Sha": "R2tiZRQgY/iohXZt5O4HaQwtVe/adWU2VOcKaelJ3Us=",
  "DefaultPayload": "C:\\ProgramData\\\\Payloads\\M4PayloadAuto.xml"
},
........
]
}

Data $http call

Where does let statement go?

let result.statuses = ['Old Device', 'New Device', 'Activated', 'Unactivated'];

 function DeviceController($http, $scope){
        var vm = this;
        var dataService = $http;
        //dataService.get("/api/Product")

        vm.devices = [];
       deviceList();

      function deviceList() {
           $http.get(_url)
             .then(function (result) {
             vm.devices = result.data.Devices;   
           },
           function(error) {
                console.log('error');
           });

Answer №1

To achieve the desired results, make adjustments to your WebApi. It appears that the device status is an enum on the server side, so you can send back the text of the enum in the api response. As for the archived items, it seems they are stored as an array/List which can be converted into a comma-separated string for the client if necessary - using string.Join(", ", yourArray).

While it's not always possible for your api to provide responses exactly in the format expected by the client, sometimes additional logic may need to be implemented on the client side to process the data accordingly. In this case, I would recommend changing the api to return an object containing both the status id and name instead of just an integer value for device status. For the archived items, consider whether it would be easier to implement the necessary changes on the server or client side.

Update: The OP has mentioned they do not have control over the api. Below is some sample code to help get started (plunker - https://plnkr.co/edit/nHLl07I0B33QMdfZoP1N?p=preview):

// Sample AngularJS code
var app = angular.module("MainModule", []);

app.controller("MainController", function() {

  var self = this;

  // Empty devices array to start with
  self.devices = [];

  // Dummy data to simulate api call and retrieve devices
  self.devices = [{
    "DeviceId": "00022B9A000000010001",
    "StagedManifestIdList": [],
    "PendingManifestId": null,
     // More data...
  }, {
    // Next device data...
  }];

});

// Adding custom filter for displaying device status
app.filter('deviceStatus', function() {

    var deviceStatusLookup = {
      1: "New Device",
      2: "Activated",
      3: "Unactivated"
    };

    return function(statusId) {
      var output = deviceStatusLookup[statusId];
      return output;
    }
 });

HTML:

<!DOCTYPE html>
<html data-ng-app="MainModule">

  <head>
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d6b7b8b1a3bab7a4f8bca596e7f8e3f8ee">[email protected]</a>" data-semver="1.5.8" src="https://code.angularjs.org/1.5.8/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body data-ng-controller="MainController as ctrl">


    <table>
      <tr>
        <td><strong>Device Status</strong></td>
        <td><strong>Staged</strong></td>
        <td><strong>Archieved</strong></td>
      </tr>
      <tr data-ng-repeat="device in ctrl.devices">
        <td>{{::device.DeviceStatus | deviceStatus}}</td>
        <td>{{::device.PendingManifestId || 'None'}}</td>
        <td>{{::device.ManifestIdList.join(", ")}}</td>
      </tr>
    </table>     
  </body>
 </html>

Answer №2

When receiving an array as data, it may look something like this:

[
    { status: 3, archived: [002, 003, 001] },
    { status: 1, archived: [] }
]

To display the status, you would need a lookup for descriptions:

let statuses = ['Old Device', 'New Device', 'Activated', 'Unactivated'];

There are different ways to display the data. You can do simple conversions in Angular:

{{statuses[item.status]}}
{{item.archived.join(',')}}

If the requirements are more complex, it is better to convert the data before assigning it to $scope:


UPDATE

For best practices, consider setting up view functions within your controller:

// usage {{statuses[item.status]}}
$scope.statuses = ['Old Device', 'New Device', 'Activated', 'Unactivated'];

// usage {{displayArchived(item.archives)}}
$scope.displayArchived = function(archives){
    return (archives.length > 0) ? archives.join(',') : 'none';
};

You can then reference these arrays and functions in your view. If needed on multiple views or if requirements become more complex, create a service with helper functions to inject into $scope when necessary.

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 initial attribute unattainable for entities processed by csv-parse

Working on parsing a csv file, I am utilizing the csv-parse library to handle the following data - userID,sysID 20,50 30,71 However, after parsing, I am encountering difficulty accessing the property generated from the first column userID. Here is the s ...

Get rid of all numbers from a jQuery selection except for the first and last

I am dealing with an array let numberArray = ["500", "600", "700", "800", "900", "1000", "1100", "1200"] My objective is to remove all elements except for the first and last ones. The challenge arises when the array contains only one value, as I must ens ...

What is the mechanism by which HttpContext is aware of a User's Roles?

One way to determine if the current user is part of a specific role is by utilizing the method below: HttpContext.Current.User.IsInRole("Administrator"); However, I am curious about how HttpContext is able to access information on which roles the user be ...

What is the best way to insert a PDF into an asp.net webpage?

I am attempting to create a functionality on my website where users can view a PDF page within the website itself. Below is the code I have written for this purpose: if (context.User.Identity.IsAuthenticated) { string SampleURL = context.Request.Curre ...

Is it possible to stop an AjaxBehaviorEvent listener or send extra information to the f:ajax onevent function?

In the controller, I have created a listener that looks something like this: public class FooController { public void doSomething(AjaxBehaviorEvent evt) { closeDialogFlag = true; .. if(!isValid){ closeDialogFlag = f ...

experimenting with a controller that includes $scope.$on functionality

Can someone help me with testing the $scope.$on functions in my modal controller? I'm not sure how to go about it. Any suggestions? $scope.$on("filesUploaded", function (e, files) { for (var i = 0; i < files.length; i++) { ...

Is there a way to dynamically expand and collapse all table rows, with the latest row always remaining visible, using pure JavaScript?

I have a form input field where I enter data. The entered data is then displayed in a table as a new row, with the most recent entry at the top. What I want to achieve is to show only the newest row in the table and hide all other rows. When I hover over ...

Every item in my array is replaced by the most recently added element

Take a look at this code snippet on JSFiddle: https://jsfiddle.net/reko91/998woow6/ The issue I am facing with my project is that every time I add an element to an array, it ends up overwriting all the existing elements with the newly added one. To repli ...

Ways to encounter the "10 $digest() iterations reached. Aborting" issue in Jasmine

There have been inquiries regarding how to handle the error message: 10 $digest() iterations reached. Aborting, One example is found in a question on Stack Overflow (here). The solution involves modifying the code to prevent changes to the $scope durin ...

Attempting to convert a Raw image file and upload it onto the server

I am currently attempting to upload an image to my server using PHP. I have two files for this task - index.php and myscript.php. Index.php <div id="results">Your captured image will appear here...</div> <h1>Mugshot Test Page& ...

iphone app for transferring data securely between clients and servers

I am currently exploring the internet for effective measures to protect data transfer. Our server runs on a combination of asp.net and/or php scripts, with an iPhone app that interacts with these scripts to display information in a user-friendly manner. T ...

Is there a way to personalize the validation message for a username already in use in Asp.net Identity 2

Is there a way to customize the validation message for an already taken username in Asp.net Identity 2 (for example, "Name XYZ is already taken")? Your help is appreciated. Thank you. ...

Detect issues using AngularJS and Restangular

I'm struggling with this code snippet: MyService.one($routeParams.wuid).doGET('test').then(function(e){ alert('ok'); }, function errorCallback(response){ alert('error'); }); When calling the API I set up ...

Front end authentication failed (Angular/Spring stack)

Link to my front end code: http://embed.plnkr.co/toe4XO/. I made adjustments to the authentication/service.js file, see below: 'use strict'; angular.module('Authentication') .factory('AuthenticationService', ['Base ...

Unable to toggle Bootstrap 5 tabs in a Nunjucks template - the issue persists

I have been following the bootstrap documentation for tabs which can be found at this link After referencing the documentation, I replicated the sample implementation in my code as shown below: --- title: Portfolio description: Portfolio --- {% exten ...

Conceal a list of items within a div that has a particular class

This is a sample of my HTML code: <div class="row"> <div class="col-md-12"> <div class="scrollbox list"> <ul class="list-unstyled"> <li id="articulate.flute">articulate flut ...

How to Retrieve Correct JSON Data from Mongoose Query in Node.js

I am currently working on an express application that utilizes mongoDB as the database and handlebars as my server-side templating engine. Unlike many applications, I have chosen not to incorporate AngularJS or Ajax into my project. One of the challenges ...

What could be causing the npm install command to not save packages in the /node_modules directory?

After running npm install to add a package, npm indicates that the installation was successful. However, upon checking the node_modules folder, I'm unable to locate the installed package. In order to access the package, I have resorted to using npm in ...

Having trouble resolving all parameters for AuthService in Angular

Launching my angular app has hit a roadblock with this perplexing error. Despite attempts to troubleshoot by removing the auth service provider and constructor reference from my component, the issue persists. As a novice in angular, I'm struggling to ...

Troubaling with AngularJS Routing issues

I am encountering an issue with my routing system. The "otherwise" case is functioning correctly, however, when I click on a menu item, the routing does not load the corresponding page automatically. Can someone assist me in identifying what is wrong with ...