The configuration error occurred for the `get` action due to an unexpected response. Instead of an object, an array was received

Despite numerous attempts, I am struggling to find a solution that works for me. In my Courses controller, I am using the Students service and Staff service to access my staff and student objects. My goal is to retrieve the staffs and students objects in order to access their name properties for display purposes. The course object only contains an array that stores staffIDs and StudentIDs. While my staff services work correctly, I encounter an error with the student service. I am attempting to compile a list of all students and staff registered for the course. Any suggestions for a cleaner implementation of my code would be greatly appreciated.

The Course Controller

(function () {
  'use strict';

  // Courses controller
 angular
.module('courses')
.controller('CoursesController', CoursesController);

CoursesController.$inject =   ['$scope','StaffsService','StudentsService','$state','$filter', 'Authentication', 'courseResolve'];

function CoursesController   ($scope,StaffsService,StudentsService,$state,$filter, Authentication, course) {
var vm = this;

vm.authentication = Authentication;
vm.course = course;
vm.error = null;
vm.form = {};
vm.remove = remove;
vm.save = save;
//Array of filtered staff
var temp = [];
$scope.liststaff = []; 
//List of all   
StaffsService.query(function(resource){
$scope.liststaff = resource;
for(var i = 0; i < $scope.liststaff.length; i++){
  if(vm.course.staff == undefined){
        vm.course.staff = [];
    }
if(vm.course.staff.indexOf($scope.liststaff[i]._id) > -1){
  $scope.liststaff[i].checked = true;
    }
  }
});

  $scope.coursesStaff = []; 
  $scope.coursesStudent = [];

//get staff courses object to get course title
if(vm.course.staff!=undefined){
 for ( var i = 0; i < vm.course.staff.length; i++) { 
     $scope.coursesStaff[i] = StaffsService.get({ staffId:    vm.course.staff[i] });     
  }
}

//Get list of students taking this course
 if(vm.course.student!=undefined){
  for ( var i = 0; i < vm.course.student.length; i++) { 
     var some = StudentsService.get({ student_Id: vm.course.student[i] });
     console.log(some);
      $scope.coursesStudent[i] = some;
  }
}


 //Filter for assigning staff to this course
 $scope.selectedStaff = function () {
    temp = $filter('filter')($scope.liststaff,({checked: true}));    
 }

// Remove existing Course
function remove() {
  if (confirm('Are you sure you want to delete?')) {

    if($scope.coursesStudent != undefined){

      for(var i = 0; i < $scope.coursesStudent.length; i++){
      var index = $scope.coursesStudent[i].course.indexOf(vm.course._id);
      $scope.coursesStudent[i].course.splice(index,1);
      var temp = $scope.coursesStudent[i];
      var id = vm._id
      StudentsService.update({id:id},temp);
      }
    }

    if($scope.coursesStaff != undefined){

      for(var i = 0; i < $scope.coursesStaff.length; i++){
      var index = $scope.coursesStaff[i].courses.indexOf(vm.course._id);
      $scope.coursesStaff[i].courses.splice(index,1);
      var temp = $scope.coursesStaff[i];
      var id = vm._id
      StaffsService.update({id:id},temp);
      }
    }
    vm.course.$remove($state.go('courses.list'));
  }
}

// Save Course
function save(isValid) {
  if (!isValid) {
    $scope.$broadcast('show-errors-check-validity', 'vm.form.courseForm');
    return false;
  }

  // TODO: move create/update logic to service
  if (vm.course._id) {
    vm.course.$update(successCallback, errorCallback);
  } else {
    vm.course.$save(successCallback, errorCallback);
  }

    for ( var i = 0; i < $scope.liststaff.length; i++) {  
    if($scope.liststaff[i].checked == true){    
      if(vm.course.staff == undefined){
        vm.course.staff = [];
      }
      if(vm.course.staff.indexOf($scope.liststaff[i]._id) == -1){

          vm.course.staff.push($scope.liststaff[i]._id); 
          var temp = $scope.liststaff[i];
          temp.courses.push(vm.course._id);
          var id = $scope.liststaff[i]._id;
          StaffsService.update({id:id},temp);
        }

      }
      //remove items tht were unchecked from parent object
      else{
        var index = vm.course.staff.indexOf($scope.liststaff[i]._id)
        if (index > -1) {
            vm.course.staff.splice(index, 1);
            var nuindex = $scope.liststaff[i].courses.indexOf(vm.course._id);
            $scope.liststaff[i].courses.splice(nuindex,1);
            var id = $scope.liststaff[i]._id;
            var temp = $scope.liststaff[i];
            StaffsService.update({id:id},temp);
        }

      } 
    }

  function successCallback(res) {
    $state.go('courses.view', {
      courseId: res._id
    });
  }

  function errorCallback(res) {
    vm.error = res.data.message;
      }
    }
     }
      })();

Student Service

 (function () {
      'use strict';

      angular
        .module('students')
        .factory('StudentsService', StudentsService);

      StudentsService.$inject = ['$resource'];

      function StudentsService($resource) {
        return $resource('api/students/:studentId', {
          studentId: '@_id'
        }, {
          update: {
            method: 'PUT'
          }
        });
      }
    })();

Staff Service

    (function () {
      'use strict';

      angular
        .module('staffs')
        .factory('StaffsService', StaffsService);

      StaffsService.$inject = ['$resource'];

      function StaffsService($resource) {
        return $resource('api/staffs/:staffId', {
          staffId: '@_id'
        }, {
          update: {
            method: 'PUT'
          }
        });
      }
    })();

HTML for output

    <section>
      <div class="page-header">
        <h1 data-ng-bind="vm.course.title"></h1>
      </div>
      <div class="pull-right"
           data-ng-show="vm.course.isCurrentUserOwner">
        <a class="btn btn-primary"
           data-ui-sref="courses.edit({ courseId: vm.course._id })">
          <i class="glyphicon glyphicon-edit"></i>
        </a>
        <a class="btn btn-primary" data-ng-click="vm.remove()">
          <i class="glyphicon glyphicon-trash"></i>
        </a>
      </div>
     <h3>Student</h3>
     <div class="list-group">
        <a data-ng-repeat="student in coursesStudent"
           data-ui-sref="students.view({ studentId: student._id })"
           class="list-group-item" >

          <h4 class="list-group-item-heading">{{student.name}}</h4>
        </a>
      </div>
     <h3>Staff</h3>
     <div class="list-group">
        <a data-ng-repeat="staff in coursesStaff"
           data-ui-sref="staffs.view({ staffId: staff._id })"
           class="list-group-item">

          <h4 class="list-group-item-heading" data-ng-bind="staff.firstname"></h4>
        </a>
      </div>

      <small>
        <em class="text-muted">
          Posted on
          <span data-ng-bind="vm.course.created | date:'mediumDate'"></span>
          by
          <span data-ng-if="vm.course.user"
                data-ng-bind="vm.course.user.displayName"></span>
          <span data-ng-if="!vm.course.user">Deleted User</span>
        </em>
      </small>
      <p class="lead" data-ng-bind="vm.course.content"></p>
    </section>

Answer №1

Your HTML currently includes: data-ng-bind="staff.firstname"> Would you mind updating it to: {{ staff.firstname }} Other than that, I am having difficulty identifying the mistake. In my experience with Angular, issues typically stem from scope-related issues. Kudos for effectively leveraging Angular Services.

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

Achieving error handling in PHP API using Phalcon framework

I am in the process of developing an API consumer service using AngularJS, while my API is built with the Phalcon micro framework. The issue I am encountering pertains to how errors are handled when the API responds. It appears that when there is an error ...

Interplay between Angular controllers and directives

I've been working on a code snippet that allows users to leave comments on a list of items. To achieve this, I created a directive and set it up to listen for keydown events in order to prompt the user to submit a comment by a specific keycode, 13. H ...

Can you run both Angular 6 and AngularJS 1.6 applications on the same computer?

Trying to juggle the development of an Angular 6 app and an AngularJS 1.6 app on the same machine has posed a challenge for me. My current situation involves working on two projects simultaneously - one being a new project utilizing Angular 6 and Angular ...

Trouble with document updates in MongoDB/Mongoose causing a delay?

I am currently working on updating an object nested in an array in my application. When I test this functionality using Postman, I am experiencing a delay that requires me to make two requests in order to see the updated value. if (taskStatus) { cons ...

Browsing through a jQuery JSON object in Chrome reveals a dynamic reshuffling of its order

Jquery + rails 4 Within the json_data instance, there is data with key-value pairs. The key is an integer ID and the value is an object containing data. However, when attempting to iterate over this data using the jQuery $.each function, the results are s ...

Transform JSON into a JavaScript array object using node.js

My knowledge of Javascript is limited and I need assistance with a .json file that has the following structure: { "results": [ { "challenger": { "__type": "Pointer", "className": "Player", "objectId": "STWAxAHKay" }, "c ...

Error Handling with Node.js Sequelize RangeError

Currently, I am in the process of setting up a table to store user sessions. Specifically, I plan to save the IP address as an integer and have been exploring various methods for achieving this. You can find more information on this topic here: IP-addresse ...

parallelLimit asynchronously executes in limited quantities once

Utilizing async.parallelLimit to update database records in batches of 10 that total 1000 each time is my current challenge. I am exploring how to implement this feature in my code but have run into some issues. Despite studying example interpretations, my ...

What is causing the Invalid left-hand side error in the postfix expression at this specific line of code?

I encountered an error stating "invalid left-hand side in postfix expression" while trying to execute this particular line of code data: 'Action=AutionMaxBid&AuctionItemID='+<?php echo $bidItemID ;?>+'', This error occurred d ...

Set up Node to utilize Object.assign

Currently, I am experimenting with Object.assign functionality in IO.js and Node.JS, but encountering an unexpected error. /Users/lp/.nvm/versions/io.js/v2.4.0/bin/iojs --debug-brk=59842 --nolazy mixin.js Debugger listening on port 59842 /Users/lp/Documen ...

Extract a free hour from the JavaScript time array without any filtering

In my Javascript array, I have the teaching schedule of a teacher for the day. { "time": [ { "start":"10:00","end":"11:00" }, { "start":"12:00","end":"01:00" }, { "start":"04:00","end":"06:00" } ] } My goal is to determine the free hours in the abo ...

Using the && operator in an if statement along with checking the length property

Why does the console show 'Cannot read property 'length' of undefined' error message when I merge two if conditions together? //When combining two if statements using &&: for(n= 0, len=i.length; n<len; n++) { if(typeof ...

Is there a way to successfully transfer both the event and props together?

For simplifying my code, I created a function that triggers another desired function when the Enter key is pressed. Here's an example of how it works: const handleKeyDown = (event) => { if (event.key === 'Enter') { event.preventDefa ...

Failure to give an error message occurred during a POST request on Parse.com and ExpressJS platform

I'm facing an issue where a POST request I send fails with error code 500 and there is nothing showing up in my server side error log. It seems like the cloud method may be missing. What's interesting is that the same POST request works fine wit ...

What is the appropriate way to incorporate a dash into an object key when working with JavaScript?

Every time I attempt to utilize a code snippet like the one below: jQuery.post("http://mywebsite.com/", { array-key: "hello" }); An error message pops up saying: Uncaught SyntaxError: Unexpected token - I have experimented with adding quotation m ...

How to automatically insert a comma into numbers as you type in Vue.js

I am trying to insert separators in my numbers as I type, but for some reason it is not working. Sample Code <el-input-number v-model="form.qty" style="width: 100%;" id="test" placeholder="Quantity" controls-position="right" v-on:keyup="handleChange" ...

Javascript only select values from the initial row of the table

I have a database that I am using to populate a table with results. To interact with these results, I utilize JavaScript in addition to PHP for retrieving values from the database and displaying them in the table. <table id="datatable" class="table tab ...

What is the best way to navigate to the top of a form panel?

I'm currently developing a Sencha Touch mobile app. I have a form panel with multiple fields, so I made it scrollable. However, every time I open the screen (panel), scroll down, navigate to other screens, and then return to the form panel, it stays s ...

Show content based on information from an array using JavaScript

I am currently working on developing a user-friendly step-by-step form using AngularJS and UI-router to navigate through different sections. The data collected from each form is stored in a JavaScript array, and I am trying to dynamically show or hide a di ...

What could be causing this track by not functioning properly in AngularJS (Angular 1.X)?

In my controller, I am assigning a value to the ng-model. I anticipate that the dropdown will synchronize (two-way bind?) with the value in the controller. function TodoCtrl($scope) { $scope.model = 'b' $scope.model2 = 'b' $sc ...