Encountered a $resource configuration issue while making a request to the SharePoint REST service with Angular

In an old sample app without angularJS, a rest service is called in the following way: This app does not use angularJS.

var listName = "Events";

        // the url to use for the REST call.
        var url = SPAppWebUrl + "/_api/SP.AppContextSite(@target)" +

            // this is the location of the item in the parent web. This is the line
            // you would need to change to add filters, query the site etc
          //  "/web/lists/getbytitle('" + listName + "')/items?" +
            "/web/lists/getbytitle('" + listName + "')/items?$select=Title,Category,EventDate,Description,EncodedAbsUrl,ID" +
            "&@target='" + SPHostUrl + "'";

        // create  new executor passing it the url created previously
        var executor = new SP.RequestExecutor(SPAppWebUrl);

        // execute the request, this is similar although not the same as a standard AJAX request
        executor.executeAsync(
            {
                url: url,
                method: "GET",
                headers: { "Accept": "application/json; odata=verbose" },
                success: function (data) {

                    // parse the results into an object that you can use within javascript
                    var results = JSON.parse(data.body);
                    var events = [];

In my new app, I have developed an angular-based app that retrieves data from a SharePoint list using rest API. However, I am facing challenges with the $resource.query command and its options.

The error message displayed is BADCFG, indicating incorrect options usage. I couldn't find relevant information in the documentation on how to set the Headers and Accept option in my code.

The Angular JS code snippet is provided below:

App.JS

var SPHostUrl;
var SPAppWebUrl;
var ready = false;

$(document).ready(function () {
    var params = document.URL.split("?")[1].split("&");
    for (var i = 0; i < params.length; i = i + 1) {
        var param = params[i].split("=");
        switch (param[0]) {
            case "SPAppWebUrl":
                SPAppWebUrl = decodeURIComponent(param[1]);
                break;
            case "SPHostUrl":
                SPHostUrl = decodeURIComponent(param[1]);
                break;
        }
    }
});

(function () {
    "use strict";
    var app = angular.module("productManagement",
                            ["common.services",
                             "ui.router",
                             "ui.mask",
                             "ui.bootstrap"]);

    app.config(["$stateProvider",
                "$urlRouterProvider",
        function ($stateProvider, $urlRouterProvider) {
            $urlRouterProvider.otherwise("/products");

            $stateProvider
                .state("home", {
                    url: "/",
                    templateUrl: "../Scripts/app/welcomeView.html"
                })
                // Products
                .state("productList", {
                    url: "/products",
                    templateUrl: "../Scripts/app/products/productListView.html",
                    controller: "ProductListCtrl as vm"
                })
                .state("productEdit", {
                    abstract: true,
                    url: "/products/edit/:productId",
                    templateUrl: "../Scripts/app/products/productEditView.html",
                    controller: "ProductEditCtrl as vm",
                    resolve: {
                        productResource: "productResource",

                        product: function (productResource, $stateParams) {
                            var productId = $stateParams.productId;
                            return productResource.get({ productId: productId }).$promise;
                        }
                    }
                })
                .state("productEdit.info", {
                    url: "/info",
                    templateUrl: "../Scripts/app/products/productEditInfoView.html"
                })
                .state("productEdit.price", {
                    url: "/price",
                    templateUrl: "../Scripts/app/products/productEditPriceView.html"
                })
                .state("productEdit.tags", {
                    url: "/tags",
                    templateUrl: "../Scripts/app/products/productEditTagsView.html"
                })

                .state("productDetail", {
                    url: "/products/:productId",
                    templateUrl: "../Scripts/app/products/productDetailView.html",
                    controller: "ProductDetailCtrl as vm",
                    resolve: {
                        productResource: "productResource",

                        product: function (productResource, $stateParams) {
                            var productId = $stateParams.productId;
                            return productResource.get({ productId: productId }).$promise;
                        }
                    }
                })

        }]
    );
}());

ProductListrCtrl.js

(function () {
    "use strict";
    angular
        .module("productManagement")
        .controller("ProductListCtrl",
                    ["productResource",
                    ProductListCtrl]);

    function ProductListCtrl(productResource) {
        var vm = this;

        productResource.query(function (data) {
            vm.products = data;
        });

        vm.showImage = false;

        vm.toggleImage = function () {
            vm.showImage = !vm.showImage;
        }
    }
}());

ProductResource.js

(function () {
    "use strict";

    angular
        .module("common.services")
        .factory("productResource",
                ["$resource",
                 productResource]);

    function productResource($resource) {
        var listName = "Products";

        // the url to use for the REST call.
        var url = SPAppWebUrl + "/_api/SP.AppContextSite(@target)" +

        // this is the location of the item in the parent web. This is the line
        // you would need to change to add filters, query the site etc
        //  "/web/lists/getbytitle('" + listName + "')/items?" +
            "/web/lists/getbytitle('" + listName + "')/items?$select=Id,productName,productCode,releaseDate,description,cost,price,category,tags,imageUrl" +
            "&@target='" + SPHostUrl + "'";

        //return $resource(url);
        //return $resource("/api/products/:productId")

        return $resource(url, {}, {
            query: { method: 'GET', isArray: true },
            create: { method: 'POST' }
        })
    }

}());

Answer №1

When it comes to including headers:

return $resource(url, {}, {
  query: { method: 'GET', isArray: true,
           headers: { "Accept": "application/json; odata=verbose" }
         },
  create: { method: 'POST' }
});

However, the issue seems to be different. The query function expects an array while the server may not be returning one. It could be due to the missing header, but based on your initial example where there is a comment parse the results into an object, it suggests that the server might not return an array regardless. In such a scenario, you can consider adding a result transformer.

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

Divs expanding below content in IE on a particular server

Currently, I am facing an issue with a JavaScript div that expands correctly over other content in most situations but goes under the content in one specific scenario. I am unsure about where to begin debugging this problem. To provide some context, the d ...

I need to know the right way to send a file encoded in Windows-1255 using Express

I'm currently developing an API that is responsible for generating text files. The purpose of this API is to support legacy software that specifically requires the use of Windows 1255 encoding for these files. To create the content of the file, I am r ...

What is the best way to dynamically update form fields in a database after making a selection in a <select> component?

Currently, I have a form that displays a list of stars (stellar objects) with a <select> control and two <inputs>. I am seeking guidance on how to populate the two inputs from the database when the user changes the selection in the <select&g ...

Why isn't Material UI Data Grid onCellEditCommit working? Wondering if anyone has insight

Having trouble retrieving the data after editing using onCellEditCommit, but it's not functioning properly. This callback is triggered when changes to a cell are committed. Signature: function(params: GridCellEditCommitParams, event: MuiEvent, deta ...

Obtain the currently selected HTML element using tinyMCE

Within my editor, I have the ability to choose text and show it using the code below: alert(tinyMCE.activeEditor.selection.getContent({format : "html"})); The problem is that this function only returns text and not HtmlElement. This means I am unable to ...

Element with adhesive properties alters its color at a particular location

I need the sticky element to change colors at specific points and then revert back to its original color. The color should be orange initially, green on block 2, and orange again on block 3. For the complete code and to address any issues with jQuery, pl ...

Connecting Angular directive to a controller

While diving into some Angular JS tutorials, I decided to apply what I learned in the Ionic framework. Unfortunately, I hit a roadblock when attempting to create a reusable HTML control because the model isn't syncing with the view as expected. Here&a ...

Identify changes in attributes on elements that are updated automatically

On my webpage, I want to have two select boxes that are connected so their values always match. Here's an example: Imagine a page with two selects: <select class="myselector"> <option value='1'>1 <br> < ...

AngularJS enhances user experience by allowing textareas to expand upon click

I am just starting to learn about angular.js and I'm wondering how to add a text area when clicking on an image. ....... ..... ..... </thead> <tbody> <tr ng-repeat="stu in Studentlist"> <td>{{stu.rollno}}</td> <td> ...

Select value not updating as expected

I have a select box that is linked to a switch statement in PHP, which changes the order of the results returned from the database based on the value selected in the select box. However, I am facing an issue with my JavaScript not working correctly. Can an ...

Mongoose JS is unable to display the query value in the output

Is there a way to use mongoose js to create a collection of kittens with specific attributes like {name: "mike"}? Once this document is created, I need to be able to view its value. I've attempted to write the following code: However, I've enco ...

What is the best way to incorporate tinymce into webpack?

I am facing an issue with integrating tinymce with webpack. It assigns a property called tinymce to window, so one solution is to use the following syntax to require() it (as explained in the bottom of the EXPORTING section of the webpack documentation): ...

I'm a beginner in React Native and I'm attempting to display a "Hello World" text when the button is pressed. Unfortunately, the code below is not

''' import { StyleSheet, Text, View, SafeAreaView, TouchableOpacity, Button } from 'react-native' import React from 'react' const handlePress = () => { <View> <Text> Greetings universe ...

Utilizing $index in AngularJS while iterating through ng-repeat items

Here is an example of an unordered list: <ul class="dropdown-menu inner" role="menu"> <li ng-repeat="availableAlphaName in availableAlphaNames" data-original-index="0" data-optgroup="1" class=""> <a tabindex="0" class="opt " st ...

What is causing the onclick event to not function properly when called from an external .js file?

I've created a .js file that contains code for a photo album application. The file includes functions for changing images when buttons are clicked. However, when I interact with the buttons, the images do not change as expected. The code in the .js f ...

Ways to send a JSON object to a Node.js server

I am working on developing a hybrid mobile application with Node.js as the backend and MongoDB for saving data. My server is functioning properly, and I have set up routes to handle user requests. While I can retrieve data from my server using the GET met ...

Display the image regardless of whether the component is currently visible

I need help with my Vue.js web application that includes a side navigation menu component. This component uses conditional rendering to display only when necessary. Within the component, there is an image for the close button of the side menu. <transiti ...

Is it possible to utilize hooks such as 'useState' within an async/await server component?

'use client' async function Teachers (){ const response = await fetch('http://localhost:8000/teachers', }) const data = await response.json(); const [showNames , setShowNames] = useState(false); // Unable t ...

What is the best way to restore a component's state to its default settings when it receives new props?

I have a Next.js project in development with a custom Layout already set up. I want the header component to reset whenever a new page is navigated to, so that the menu reverts back to its default state. Does anyone know how I can achieve this? import { F ...

What is the process for creating a list using layers that are published in Geoserver?

I am currently working on developing a webmapping application. One of the tasks I need to accomplish is parsing the WMS request in order to retrieve the title of each layer within the layers section: var xhr = new XMLHttpRequest(); xhr.open(' ...