Ensuring the accurate promise is delivered in Angular

I'm struggling to correctly return the promise for a service in Angular.

Here is the function causing me trouble:

postToSP.post($scope.sharePointURL, data).then(function() {
            $scope.gettingData = false;
            $scope.yammerListName = "Successfully posted to SP"; 
        }).catch(function(e){
                        //console.log("Error: ", e);
                        $scope.yammerListName = "Sorry we couldn't post to that page, please make sure your column names are EXACTLY the same!"
                        $scope.gettingData = false;
                        throw e;
});  

I am receiving an error message in my service: "Unable to get property 'then' of undefined or null reference". I understand that this is due to not properly returning the promise, but I am struggling to figure out how to do it correctly. Any help would be greatly appreciated. Thank you.

app.service("postToSP", function($http) {
        //Submit to SharePoint function
        this.post = function(originalurl,data){

            console.log(data);

            var url = originalurl.split("Lists/")[0];
            var listname = originalurl.split("Lists/")[1].split("/")[0];

            var i = 0;
            return letsPost(i);

            function letsPost (i) { 

                if (data[i].checked == false) {
                      i++;
                      return letsPost(i);
                } else {

                    var formattedText = document.getElementById("text"+i).innerHTML.toString() ;
                    var formattedCreated = document.getElementById("created"+i).innerHTML.toString();
                    var formattedLikes = document.getElementById("likes"+i).innerHTML.toString();
                    var formattedLinks = document.getElementById("links"+i).innerHTML.toString();

                    var uploadData = { 
                         '__metadata': { 'type': 'SP.Data.' + listname + 'ListItem' },
                        'Title': i + "",
                        'Likes': formattedLikes,
                        'Post_x0020_Date': formattedCreated,
                        'Post_x0020_Links' : formattedLinks,
                        'Post_x0020_Text': formattedText
                    };

                    console.log(uploadData);

                    createListItem(url, listname, uploadData)
                    .done(function (columnData) {
                        console.log('Added row' + i);
                        
                        if (i < data.length) {
                            i++;
                            return letsPost(i);
                            
                        } else {
                            return;
                        }
                    })
                    .fail(function (error) {
                        console.log(JSON.stringify(error));
                        alert("Error:" + JSON.stringify(error));
                        throw error;
                    });

                    function getFormDigest(webUrl) {
                        return $.ajax({
                            url: webUrl + "/_api/contextinfo",
                            method: "POST",
                            headers: { "Accept": "application/json; odata=verbose" }
                        });
                    };

                    function createListItem(webUrl, listName, itemProperties) {

                        $.ajax({
                            url: url + "/_api/web/lists/getbytitle('" + listName + "')/items",
                            method: "GET",
                            headers: { "Accept": "application/json; odata=verbose" },
                            success: function (data) {
                                console.log(data.d.results);
                            },
                            error: function (data) {
                                console.log(data);
                            }
                        });

                        return getFormDigest(webUrl).then(function (data) {

                            return $.ajax({
                                url: webUrl + "/_api/web/lists/getbytitle('" + listName + "')/items",
                                type: "POST",
                                processData: false,
                                contentType: "application/json;odata=verbose",
                                data: JSON.stringify(itemProperties),
                                headers: {
                                    "Accept": "application/json;odata=verbose",
                                    "X-RequestDigest": data.d.GetContextWebInformation.FormDigestValue
                                }
                            });
                        });
                    };
                };
            };
        };
});

Answer №1

Start by defining the promise in your function

this.post = function(originalurl,data){
var deferred = $q.defer();

To return the desired data, use

deferred.resolve(dataToReturn)

Finally, include the following at the end of your function

return deferred.promise;

Answer №2

It seems that the issue in your code lies in returning the promise from getFormDigest and then chaining another then function on it. By not returning getFormDigest, nothing will be returned as it is an asynchronous operation.

An approach to resolve this could be utilizing the angular $q library to create a separate promise. Inside the then function, resolve this new promise instead of returning getFormDigest. This way, only one promise will be returned, potentially resolving your problem.

Answer №3

Here is a straightforward method to achieve this. Hopefully it all makes sense.

//Controller Code
 yourService.addData(yourPayload);
    .then(function (cou) {
     $scope.data = cou.data;
 });

//Service Code
this.addData = function (data) {      
    var response = $http({
        method: "POST",
        url: 'your url',
        data: data,
        dataType: "json"
    });
    return response;
}

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

"Retrieve a specific object from a JSON file using NextJS based on its ID

NextJs is the framework I am currently utilizing for my project. Is there a way to render a specific project based on its unique ID? { “projects”: [ { "id": 1, "picture": "portf.jpg" }, { ...

Exploring the process of retrieving array elements from an AJAX response transmitted from PHP

Here is an example of jQuery code for an ajax function: $(document).ready(function() { $("#zip_code").keyup(function() { var el = $(this); var module_url = $('#module_url').val(); if (el.val().length === 5) { $.ajax({ ...

retrieving an element from a collection of objects

For a project utilizing the openweather api, I encountered fluctuating data based on the time of day it is viewed. My goal is to loop through the first 8 objects to identify a dt_txt value of 12:00:00. Once found, I intend to store this result in a variabl ...

Preventing cross-site scripting attacks with the help of dynamic pre elements

An expert recommended that the user content, replyContent, be surrounded by a <pre> tag to prevent XSS attacks. However, why is it commonly believed that this code effectively prevents XSS? I attempted to inject </pre><script>alert("XSS" ...

Utilizing AngularJS: Dynamically employ custom directives for enhanced reusability

I am currently developing my debut single page Angular.js application and finding myself in a bit of a rut when it comes to programmatically compiling/evaluating a custom directive to insert it into the DOM from within a controller. The custom directive I ...

Encountering an error while configuring webpack with ReactJS: Unexpected token found while

I'm attempting to update the state of all elements within an array in ReactJS, as illustrated below. As a newbie to this application development, it's challenging for me to identify the mistake in my code. closeState(){ this.state.itemList.f ...

Using express.js to transfer an uploaded image to Amazon S3

Currently, I am faced with an issue of passing an image uploaded from a react application through express to a managed s3 bucket. The s3 bucket is created and managed by the platform/host I am using, which also generates upload and access urls for me. So f ...

Working with AngularJS to parse a JSON file

I'm struggling to access the object in a json file. This is my code: .controller("ListController", ["$scope", "$http", function($scope, $http){ $http.get('../scripts/bbtv.json').success(function(data) { $scope.artists ...

The Hydration error is caused by dynamic imports in NextJS v14.2.3

While updating NextJS from v13 to v14, I encountered a Hydration error due to dynamic imports. Is there a way to resolve this issue? const MyComponent = dynamic(() => import('../components/MyComponent')) Is there a fix that allows for both la ...

Adding a class to an element in AngularJS

I have a question about entering empty values in an input field and highlighting its boundary. I added a new class 'warning' for this purpose and created the following code. HTML: `<body ng-app="TestPage"> <form ng-controller="TestFor ...

Error message: "Angular dependencies and provider not accessible"

I recently came across a file upload script on Github that I decided to implement. <script type="text/javascript" src="{% static 'bower_components/angular-file-upload/angular-file-upload.min.js' %}"></script> Furthermore, I have cre ...

Having trouble with jqGrid data format?

Having some trouble with jqGrid and displaying data in a treeview format. The issue is that the 6th item (cid=6) is not appearing in the grid. Additionally, it seems like the 4th item may have subitems, but expanding that branch reveals nothing. I cannot f ...

Create the key's value in a dynamic manner within localforage

When utilizing localForage to store data offline, I encountered an issue with generating unique key values for each form submission. My goal is to have the key value generated dynamically as 'activity_1', 'activity_2', 'activity_3& ...

CSS modified after opening a modal dialog that has loaded external HTML content

Within my ASP.NET MVC project, I am utilizing a tab wizard. On one of the tabs, I trigger a modal dialog by loading HTML content from an external API. However, once I close the wizard and navigate to the next tab, the table style (specifically border color ...

Verify that the text entered in the form is accurate, and if it meets the required criteria, proceed to the next

Is it possible to achieve this without using JavaScript? If not, I'd like to find the simplest solution. I have a form that functions similar to a password entry field, and I would like to redirect users to a certain page if they type in a specific p ...

How can I prevent my mouse click from being overridden by my mouse hover?

Currently, I am developing a Sudoku game using JavaScript and facing some challenges with mouse events. My goal is to enable users to hover over a square and have it change color, as well as click on a square to highlight the entire row, column, and quadra ...

What is the best way to retrieve an ID from a select multiple using Element?

I am working on a select element for assigning persons to a project. My goal is to send the ID of the selected person object to a specific function. Here is what I have tried so far: <el-form-item label="Assign to:" prop="person"> & ...

Looking for assistance with my MEAN stack To Do App project development

For a test at an enterprise, I have been tasked with creating a "to do APP" using Node js, Express, MongoDB & Angular Js. This is new territory for me as I have never worked with the MEAN Stack before but I am excited to explore it! The base project has al ...

Changing a "boolean bit array" to a numerical value using Typescript

Asking for help with converting a "boolean bit array" to a number: const array: boolean[] = [false, true, false, true]; // 0101 Any ideas on how to achieve the number 5 from this? Appreciate any suggestions. Thanks! ...

Using THREE.js to incorporate a stroke above extruded text

Looking to enhance text with a horizontal line above it: var geo = new THREE.TextGeometry("x", geometry_options); var mat = new THREE.MeshBasicMaterial({color: 0, side:THREE.DoubleSide}); geo.computeBoundingBox (); var vec = new THREE.Shape(); vec.moveTo( ...