AngularJS issue: [filter:notarray] The expected data type was an array, but instead received: {} while using a filter within an ng

I'm working on populating an HTML table by making an angular request to an API using the ng-repeat directive. The HTML page loads first, and then the data is fetched from the API to fill the table once the response is received. When I include a filter in the ng-repeat directive, the table gets populated, and the filter works correctly. However, I encounter the following error in my Chrome browser console:

Error: [filter:notarray] Expected array but received: {} http://errors.angularjs.org/1.4.3/filter/notarray?p0=%7B%7D at REGEX_STRING_REGEXP (angular.js:68) at angular.js:18251 at Object.fn (app.js:185) at Scope.$get.Scope.$digest (angular.js:15683) at Scope.$get.Scope.$apply (angular.js:15951) at bootstrapApply (angular.js:1633) at Object.invoke (angular.js:4450) at doBootstrap (angular.js:1631) at bootstrap (angular.js:1651) at angularInit (angular.js:1545)

I have set up a sample on Plunker where you can see the error in the console when running the sample:

http://plnkr.co/edit/J83gVsk2qZ0nCgKIKynj?

The HTML code:

<!DOCTYPE html>
<html>
<head>
  <script data-require="angular.js@*" data-semver="1.4.3" src="https://code.angularjs.org/1.4.3/angular.js"></script>
  <script data-require="angular-route@*" data-semver="1.4.3" src="https://code.angularjs.org/1.4.3/angular-route.js"></script>
  <script data-require="angular-resource@*" data-semver="1.4.3" src="https://code.angularjs.org/1.4.3/angular-resource.js"></script>
  <script type="text/javascript" src="example.js"></script>
  <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.0/css/bootstrap-combined.min.css" rel="stylesheet" />
</head>
<body ng-app="inventoryManagerApp">
  <h3>Sample - Expected array error</h3> Filter
  <input type="text" id="quoteListFilter" class="form-control" ng-  model="search" />
  <div ng-controller="QuoteController">
    <table class="table table-bordered">
      <tbody>
        <tr>
          <th>Specification</th>
          <th>Quantity</th>
        </tr>
        <tr ng-repeat="quote in quotes | filter:search">
          <td>{{quote.SpecificationDetails}}</td>
          <td>{{quote.Quantity}}</td>
        </tr>
      </tbody>
    </table>
  </div>
</body>
</html>

The JavaScript code:

var inventoryManagerApp = angular.module('inventoryManagerApp', [
  'ngResource',
  'quoteControllers'
]);

var quoteControllers = angular.module('quoteControllers', []);

quoteControllers.controller("QuoteController", ['$scope', 'filterFilter', 'quoteRepository',
  function($scope, filterFilter, quoteRepository) {

     $scope.quotes = quoteRepository.getQuoteList().$promise.then(
            function (result) {
                $scope.quotes = result;
            },
            function () {
            }
        );
  }
]);

inventoryManagerApp.factory('quoteRepository',
  function($resource) {
    return {
      getQuoteList: function() {
        return    $resource('http://drbsample.azurewebsites.net/api/Quotes').query();
      }
    };
  });

It seems like the issue is related to the data needed for the ng-repeat directive not being available immediately upon page load. When I manually input the JSON data instead of fetching it from the API, the error does not occur.

Answer №1

There is an issue with this task:

$scope.quotes = quoteRepository.getQuoteList().$promise.then(
        function (result) {
            $scope.quotes = result;
        },
        function () {
        }
    );

The .then() function returns a new promise object for chaining: .then().then(), which results in the error message 'notarray' because it returns an object.

To prevent a reference error, you should initialize $scope.quotes as an empty array beforehand and then assign the results to it.

$scope.quotes = [];
quoteRepository.getQuoteList().$promise.then(
        function (result) {
            $scope.quotes = result;
        },
        function () {
        }
    );

Answer №2

$scope.quotes = quoteRepository.getQuoteList().$promise.then(

Removing the assignment $scope.quotes = from the code line should resolve the issue.

The object returned by promise.then is redundant for a repeat statement.

Answer №3

The $http legacy promise methods .success and .error have been phased out and will no longer be supported in Angular v1.6.0. It is recommended to utilize the standard .then method instead.

With the updated .then method, the response object now contains multiple elements such as data, status, and more. Therefore, it is necessary to access response.data specifically rather than just response:

$http.get('https://example.org/...')
  .then(function (response) {

    console.log(response);

    var data = response.data;
    var status = response.status;
    var statusText = response.statusText;
    var headers = response.headers;
    var config = response.config;

    console.log(data);

});

Answer №4

quoteGrabber.retrieveQuotes().then(
    function (data) {
        $scope.fetchedQuotes = data;
    },
    function () {
    }
);

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

Issue with dynamic form JavaScript functionality after removing curly braces { } from a select tag in Rails

In my Rails form, there is a gender field defined as follows: <%= f.select :gender, ["Male","Female"],{class: "gender"} %> I also tried adding an onclick event like this: <%= f.select :gender, ["Male","Female"],{class: "gender"},onclick: "categ ...

What is the best way to retrieve elements from this JSON data?

Currently, I am developing a command line interface to display random quotes. I have found an API to fetch quotes from, but the issue is that the JSON response is returned as an array. [{"ID":648,"title":"Jeff Croft","content":"<p>Do you validate ...

What is the correct way to write a for loop in Angular/JavaScript to initialize a form?

I am working on a form and I am trying to create a loop based on the size of my matches array: pronoPlayer0:['',Validators.required] pronoPlayer1:['',Validators.required] pronoPlayer2:['',Validators.required] I am unsure o ...

Transform a complex PHP array into JSON format using JavaScript

I have a three-tiered PHP array with both numeric indices and key-value pairs. I would like to convert it to JSON, and reiterate through the object list. How would I do this? The PHP array is called $main_array, and appears as: Array( [0] => Arra ...

Display React component when clicked

As a newcomer to the world of React, I find myself intrigued by its potential. However, I am still in the process of grasping the fundamental concepts and would greatly appreciate any explanations provided. My goal is to display an 'About' compo ...

What is the process for "unleashing" the X Axis following the execution of chart.zoom()?

After setting the scroll strategy to setScrollStrategy(AxisScrollStrategies.progressive), I noticed that my chart was scrolling too quickly due to the fast incoming data. To address this, I decided to set a specific initial zoom level for the chart using c ...

Vue.js does not seem to be properly assigning attributes that are declared within the data object array

Trying to get a hang of vue.js and looking to create dynamic product cards using it: This is the snippet from my HTML file: <div id="app"> <card v-for="products in product" :productname="product.productname"></card> </div> Here&a ...

What is the best way to manage a session using JavaScript?

Currently developing a website that initially hides all elements except for the password box upon loading. Once the user enters the correct password, all webpage elements are revealed. Seeking a solution to keep the elements visible on reload by utilizing ...

Tips for navigating to a specific row within a designated page using the Angular Material table

Utilizing angular material, I have set up a table with pagination for displaying data. When a user clicks on a row, they are redirected to another page. To return to the table page, they must click on a button. The issue arises when the user needs to retu ...

The conversion from a relative path to an absolute path in Node is producing unexpected results

Hello everyone, I'm facing a problem with the function sendDownload(), specifically with the objPathArray parameter that I am receiving in this format: [{"pathToFile":"./REPORTS/portfolio/onDemand/Portfolio_report_HP_17.08.2021.xlsx","file":"Portfolio ...

The icon for the weather on openweathermap is currently not displaying

Take a look at what my webpage looks like: http://prntscr.com/dg6dmm and also check out my codepen link: http://codepen.io/johnthorlby/pen/dOmaEr I am trying to extract the weather icon from the api call and display that icon (e.g. "02n") on the page base ...

Updating JSON data post XMLHttpRequest call

Currently experiencing a puzzling moment. I'm attempting to insert more information into my object after retrieving it from an external source (just for testing purposes, I intend to add random values). Without further ado: As an example, here is w ...

Struggling to find the pathway to access a JavaScript file

I am a beginner in the world of web development and I am currently experimenting with node.js along with express. Here is the structure of my directory: First App ----node_modules ----public --------scripts ------------additems.js ----views - ...

Organizing the directory layout for the /profile/username/followers route in NextJs

I want to set up a folder structure for my website that can accommodate the URL /profile/username/followers, where the username will be different for each user. The proposed folder structure is as follows: pages -- profile -- [username].js Curren ...

Start a Draft.js Editor that includes an unordered list feature

I am trying to pre-populate a draft.js editor with an unordered list made from an array of strings. Here is the code I have so far: const content = ContentState.createFromText(input.join('*'), '*') const editorState = EditorState.crea ...

Kendo Grid with locked height

Using a grid with some elements locked, we have established a CSS-defined minimum and maximum height for the grid. .k-grid-content { max-height: 400px; min-height: 0px; } An issue arises when setting the height of the locked grid. If the grid&a ...

Develop a CakePHP CRUD view using a JavaScript framework

Creating a CRUD view in Cake PHP is simple with the following command: bin/cake bake all users This command builds the users table for CRUD operations. Is there a JavaScript framework that offers similar simplicity? ...

What is the process behind executing the scripts in the jQuery GitHub repository when running "npm run build"?

Check out the jQuery repository on GitHub. Within the jQuery repo, there is a "build" folder. The readme.md mentions the npm command: npm run build This command triggers the execution of scripts in the build folder to complete the building process from ...

Arrange the array to show 8 elements, ensuring to first review the likes object within the array

I am currently iterating through an array of objects in the following manner: <% for(post of posts) { %> <% if(post.likes > 5){ %> <div class="col"> <div class="ca ...

Tips on storing chosen language in local storage or cookies using AngularJS

As a newcomer to angularjs, I am facing the challenge of saving the selected language from a dropdown menu in HTML to either local storage or cookies. This way, when a user navigates to another page, the language they previously chose will be loaded and us ...