Transforming JavaScript's POST Ajax into AngularJS' POST Factory

I am attempting to convert an Ajax call with WSSE authentication into an AngularJS factory. The request method is Post.

The purpose of this conversion is to access the Adobe Analytics Rest API, retrieve data in JSON format, and then visualize it using d3.js.

I am unfamiliar with the properties that can be utilized in an AngularJS $http post call, making me unsure about the correct approach for implementing WSSE auth, dataType, callback, etc. Below is the original ajax code obtained from a public github repository:

(function($) {
  window.MarketingCloud = {
    env:   {},
    wsse:  new Wsse(),

    /** Make the api request */
    /* callback should follow standard jQuery request format:
     *    function callback(data)
     */
    makeRequest: function (username, secret, method, params, endpoint, callback)
    {
        var headers = MarketingCloud.wsse.generateAuth(username, secret);
        var url = 'https://'+endpoint+'/admin/1.4/rest/?method='+method;
        $.ajax(url, {
            type:'POST',
            data: params,
            complete: callback,
            dataType: "text",
            headers: {
                'X-WSSE': headers['X-WSSE']
            }
        });
    }
  };
})(jQuery);

This is how the current code is being used with pure JS:

MarketingCloud.makeRequest(username, secret, method, params, endpoint, function(response) {
        data = JSON.parse(response.responseText);
});

I aim to transform this into a factory and controller respectively.

Here is what I have implemented for the factory so far:

app.factory('mainFactory', ['$http', function($http) {
  var wsse = new Wsse();
  return function(username, secret, method, params, endpoint) {
    return $http({
      method: 'POST',
      url: 'https://' + endpoint + '/admin/1.4/rest/?method=' + method,
      data: params,
      headers: {
        'X-WSSE': wsse.generateAuth(username, secret)['X-WSSE']
      },
      dataType: 'text',
    });
  };
}]);

And here is my implementation for the controller:

app.controller('mainController', ['$scope', 'mainFactory', function($scope, mainFactory) {
  mainFactory.success(function(data) {
    $scope.data = data;
  });
}]);

Currently facing an error stating

mainFactory.success is not a function
, which suggests that the factory isn't functioning correctly yet.

Answer №1

I have successfully resolved the issue on my own. It turns out that the parameters I was passing to the initial function in the factory were already globally defined and being overwritten. As a result, the first function is unnecessary.

Below is the code for the factory:

app.factory('mainFactory', ['$http', function($http) {
  var wsse = new Wsse ();
  return {
    getAnalytics : function (){
      $http({
          method: 'POST',
          url: 'https://' + endpoint + '/admin/1.4/rest/?method=' + method,
          data: params,
          headers: {
            'X-WSSE': wsse.generateAuth(username, secret)['X-WSSE']
          }
        })
        .success(function(data) {
          return data;
        })
        .error(function(err) {
          return err;
        });
    }
  };
}]);

And here is the controller section of the code:

app.controller('mainController', ['$scope', 'mainFactory', function($scope, mainFactory) {
  $scope.title = "Inn Site";
  $scope.data = mainFactory.getAnalytics();
}]);

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

Tips for determining the presence of a query string value using JavaScript

Is there a way to detect the presence of q= in the query string using either JavaScript or jQuery? ...

Tips for converting a "callback pyramid" into a promise-based structure

I'm currently struggling with understanding how to refactor my code to use promises or the Q library effectively. Let's consider a common basic example: I have a test case that imports the same file twice into a MongoDB database and then checks ...

Error encountered when trying to show a modal using a PHP script

I'm encountering an issue with the modal system on my website. Let me share some code snippets: MODALS ARE BUILT WITH W3.CSS LIBRARY modal.js (including debug statements) let modal = null; let title = null; let content = null; $(document).ready(() = ...

Consistent Errors with AJAX POST Requests Despite CORS Enablement

Here is a function I have created for making an ajax post request: function POST(url, data) { $.ajax({ 'type' : "POST", 'url' : url, 'data' : data, headers : { 'Access-Cont ...

Ways to properly release file descriptors in write streams

I'm currently working on a code snippet that showcases what I'm aiming to achieve: const fs = require('fs'); var stream = fs.createWriteStream('/tmp/file'); stream.once('open', function(fd) { for (var i = 0; i ...

What is the best way to make a Firestore request that relies on the initial Firebase response in Next.js?

Is there a way to perform a second cloud Firestore query using the uid obtained in the first query, without the second query executing before receiving the response from the first one? Here's my code: var {data} = useSWR('/api/report', fet ...

Challenges with Angular scoping

I am facing an issue with a form in my ng-controller where it doesn't seem to update the properties in the controller as expected. After some research, I realized my misunderstanding of prototypal inheritance. Thanks to information from the internet a ...

Tips on implementing href with "javascript:window.open..." in AngularJS

I've been trying to utilize an anchor tag in my HTML code to open a new modal browser window with a URL retrieved through an Angular value like this: <a href="javascript:OpenPopUpPage('{{listing.Linktest}}');">Test Link</a> Alt ...

Receiving data through multiple ajax calls nested within another ajax call

Hello everyone, I am diving into the world of AJAX/jQuery and would appreciate your patience as I try to navigate through it. I have an interesting challenge ahead so let's see how we can tackle it together ...

My attempts to troubleshoot the JavaScript function have all been unsuccessful

I am completely new to JavaScript and feeling a bit embarrassed that I'm struggling with this. My goal is to build a website that takes first and last names as input and generates email addresses based on that information. Despite my attempts, moving ...

To link the information within the angularJS controller

I've recently generated a div element dynamically within the controller function of my AngularJS application. However, I'm facing an issue where the data is not binding as expected inside this div element. Here is a snippet of my code: function ...

Retrieve a collection of items based on their data-id attribute

I need to create a list of label elements with data-id attributes. I will use the values from these labels to set images on the main container. The function changeimage is returning a nodelist with null elements, but I am not sure why this is happening. ...

Opt for JavaScript DOM manipulation over jQuery for element selection without depending on jQuery

I am attempting to target a specific element using JavaScript: element = '<div class="c-element js-element">Something Here</div>'; When I try to select this element with the following code: $(element) The result is not as expected ...

Ways to access device width and height in React without relying on the window object

How can I retrieve the device width or height in React or Next.js without using "window" or "document"? I know that we can achieve this with the useEffect hook to avoid encountering the error: ReferenceError: window is not defined However, using useEffect ...

Saving the object returned by the useRef hook into the Redux state

I have a question. I am developing a music platform similar to Spotify using Next.js. To manage states, I am utilizing Redux Toolkit. In order to play music, I have integrated the audio element within a component that includes controls to adjust the music ...

What is the best way to execute useEffect in React Router?

Struggling to get my useEffect function to run properly in a React app using a REST API for a Inventory Management application. The issue seems to be with setting the item variable. Any insights on why this might be happening? Item.jsx: import React, { us ...

Sorting an array of Material-UI's <TableRow> alphabetically using ReactJS and Material-UI. How to do it!

I am currently utilizing Material-UI's <Table> and <TableRow> components by rendering an array of <TableRow>s using the .map() method. Each <TableRow> contains a <TableRowColumn> representing a first name, for example: &l ...

Implement a jQuery slider that pauses on hovering

Currently, I am grappling with the clearInterval function in a small jQuery project. To better illustrate the issue, I have created a jsFiddle example: http://jsfiddle.net/eWTSu/ While the rotation works smoothly, I encountered an obstacle when hovering ...

Guide on posting an object in Angular through HTTP Post

I am attempting to send an object named Pack to my API Rest server using my Angular service. Below is the function I have set up for this task: save_pack(Pack: any){ return new Promise((resolve, reject) =>{ this.http .post("http://loca ...

Sorting a targeted section of an already organized 2D Array based on updated values, solely if the initial sorted values align in Javascript

A challenging scenario I need help with involves an array containing objects, each with a score and a rank as shown below: [ { "score": 20, "rank": 12 }, { "score": 20, "rank": 7 }, { "score": 34, "rank": 4 } ] To begin w ...