Performing an additional GET request using AngularJS

After successfully running the code snippet, I received the JSON output displayed below. My main focus now is on extracting the cars_url. What would be the most effective method to retrieve the URL (and what approach is recommended), and subsequently initiate a secondary GET request?

JSON Output

{
    created: "2013-11-08T18:57:44",
    domain: "www.test.com",
    cars_url: "/api/v1/carlot/4",
    image: null,
    modified: "2013-11-08T18:57:44"
}

JavaScript Function

app.factory('CbgenRestangular', function(Restangular) {
    return Restangular.withConfig(function(RestangularConfigurer) {
        RestangularConfigurer.setBaseUrl('http://127.0.0.1:8000');
    });
});


app.controller("CampaignData" ,
               [
                   '$scope',
                   'Restangular',
                   'CbgenRestangular',
                   function($scope, Restangular, CbgenRestangular){
                       CbgenRestangular.one('api/v1/person', "james").get().then(
                           function(person) {
                               $scope.person = person;
                               console.log(person)
                           }
                       );
                   }
               ]);

Answer №1

app.controller("CampaignDataHandler" , ['$scope', 'RestangularService', 'CbgenRestangularService', '$http',
    function($scope, RestangularService, CbgenRestangularService, $http){

        CbgenRestangularService.one('api/v1/user', "james").get().then(function(user) {
                $scope.user = user;
                console.log(user);
                var cars = $http({method: 'GET', url:user.cars_url);
                cars.then(function(data){
                     // handle success response here
                }, function(data){
                     // handle error response here
                });
            }
        );

}]);

Nesting multiple requests can become complex; using $q to manage request flow is recommended in such scenarios.

app.controller("CampaignDataHandler" , ['$scope', 'RestangularService', 'CbgenRestangularService', '$http', '$q',
    function($scope, RestangularService, CbgenRestangularService, $http, $q){
    $scope.user = {cars_url:"your 404 url here"};

    var userCall = CbgenRestangularService.one('api/v1/user', "james").get();
    $q.when(userCall.then(
        function(user) {
            $scope.user = user;
            console.log(user);
        }
    ))
    .then(function(){
        var cars = $http({method: 'GET', url:$scope.user.cars_url);
        cars.then(function(data){
             // handle success response here
        }, function(data){
             // handle error response here
        });
    });
}]);

Answer №2

If you're looking to trigger this function whenever $scope.person is updated (which typically occurs when the response from the person request comes in), one approach could be setting up a $watch in your controller.

$scope.$watch('person', function(newPerson, oldPerson){
    // Don't react to Angular's initial broadcast
    if(!newPerson){
        return false;
    }
    CbgenRestangular.one(newPerson.cars_url).get().then(function(data){
        // Handle cars data here
    });
});

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

What is an alternative method for invoking a child function within a parent component in React?

I managed to successfully call a function in a child component from a parent component in React without using refs. However, I'm unsure if my approach is just a cheap hack. Is there a better way to accomplish this task? While I've been reading t ...

Master the art of adjusting chart width on angular-chart with the help of chart.js

I am currently using angular-chart along with Angular and chart.js to create multiple charts on a single page. However, I am facing an issue where each chart is taking up the entire width of the screen. I have tried various methods to limit the width based ...

Trouble with Vue: Sibling components unable to communicate

I am encountering an issue while trying to pass data from typing.js to ending-page.js within sibling components. Despite my efforts, the emit and event hubs are not functioning as expected. However, emitting from typing.js to the parent component works sea ...

What is the process of generating a fresh JavaScript object using GWT JSNI?

Is there a way to create a new JavaScript object from GWT using JSNI? I can't seem to find any information in the documentation. I did manage to make it work by moving all the JS code to .html files, but that caused another unrelated problem. Here is ...

What is the best way to store values from dynamically generated input fields into a single database column?

In my application, I have implemented 2 dynamically added input fields. My goal is to insert the values from these two fields into separate columns in the database. <div class="form-group "> <div id="itemRows" class="col-md-12"> & ...

Unpredictable preset inline styles for HTML input elements

While developing a full-stack MERN application, I encountered an unusual issue when inspecting my React UI in Chrome DevTools. If any of these dependencies are playing a role, below are the ones installed that might be contributing to this problem: Tail ...

Hide the selection box when hovering over the Div

Looking for a quick solution. I want the option drop down to close when another div element is hovered over. First, open the drop down and hover over the red element on the right side. When hovering over the red element, I would like the drop down to clos ...

Is there a better method to accomplish this task in a more effective manner?

Is there a more efficient way to achieve this code with fewer lines of code? I'm looking for a solution that avoids repetition and makes it easier to manage, especially since I plan on creating multiple instances of this. Performance is a key consider ...

Tips for creating a page that submits itself

Currently working on a PHP script that will automatically submit an ID to itself and trigger an auto refresh to send data to the updated page. Is it feasible to use the meta refresh tag for this purpose? ...

In Internet Explorer 9, the cursor unexpectedly moves up above the element

Within my MVC3 application, I have implemented a feature to change the cursor when hovering over an element. Below is the JavaScript code that accomplishes this: $('#print').hover(function () { var cursorUrl = 'url(@Url.Content("~/Cont ...

Optimal approach for incorporating AJAX/jQuery functionality to both append to a form and refresh a list simultaneously on a single webpage

Currently, I am developing a page that consists of a form to input data into a table, as well as a list displaying items from that table. My goal is to ensure that the newest items appear at the top of the list after the form submission. At the moment, t ...

Difficulty displaying a progress bar over an overlay

Issue with Progress Bar Visibility in AJAX Call: I have a requirement to display a progress bar in an overlay after the save button is clicked. However, the progress bar is only visible after we receive the response from the AJAX call and display an aler ...

Can you iterate through each element that matches those in a different array?

As a beginner in Javascript, I may stumble upon some obvious errors, so please bear with me. My goal is to iterate through two arrays and perform a loop for each element that exists in both arrays. Currently, this is my code: if(obtainedCards.some( sp =& ...

Incorporating a full-page background into a specific view using AngularJS

In order to implement a fullscreen CSS background for a specific view in my app, I attempted adding a class to the body. However, this approach caused the background to persist in the cache and remain visible when switching views. The challenge arises fro ...

Preventing AngularJs from Overriding VueJs Routes: Ensuring VueJs Routes Remain Uninterrupted

Currently, I am the steward of a substantial legacy ecommerce web application (constructed with AngularJS) and am in the process of completely reimagining it using VueJs. It is necessary for both applications to operate concurrently (until all existing fu ...

Failure to recognize AJAX content in .ready function

When using an AJAX call to load content, primarily images, I encountered a challenge. I wanted the div to fade in only after all the images were fully loaded. To achieve this, I made use of .ready method in jQuery. However, it seemed like the images were n ...

Polymerfire: Unable to locate a default bucket

Having an issue with uploading data to the storage Bucket of my app. The line var uploadRef = firebase.storage().ref(); is triggering this error message: Firebase Storage: No default bucket found. Ensure the 'storageBucket' property is set when ...

The transformation of all relative URLs into absolute URLs is carried out

The issue at hand seems to be peculiar to Chrome and Firefox, as IE does not exhibit the same behavior. In my angular application, I've noticed a strange phenomenon. Once a specific view is loaded, all XHR requests made using relative paths are autom ...

Leveraging the array for fetching JSON data

I'm currently utilizing this code snippet to parse json data: $.getJSON(geocodingAPI, function (json) { // Extracting variables from the results array var address = json.results[0].formatted_address; console.log('Address : ', a ...

Issues arise with the functionality of custom jQuery sliders

I'm attempting to create a bootstrap panel slider using my own jQuery code, but it's not functioning as anticipated. My Objective: I have two links for "previous" and "next", and three panels with distinct headings. When the "previous" link is ...