Leveraging AngularJS with API integration

Struggling to grasp the inner workings of AngularJS while attempting my initial API calls, I hit a roadblock.
I'm aiming to execute 2 API calls but can't seem to get it right.

Following the first $http.get, I intend to make another call (using the data from the previous call) but it's not functioning as expected. (No alert is being triggered)

The retrieval of city and country data works seamlessly after the initial .get operation

JavaScript Code:

var app = angular.module('weather', []);

app.controller("weatherCtrl", function($scope, $http) {
    $http.get("http://ipinfo.io/json").then(function(response) {
        $scope.city = response.data.city;
        $scope.country = response.data.country;  

        var apiKey = "";
        var apiCall = "api.openweathermap.org/data/2.5/weather?q=" + response.data.city + "&APPID=" + apiKey;   

        $http.get(apiCall).then(function(responsew) {
            // $scope.temperature would receive a value at this point
            alert("1")
        });
    });
})  

HTML Structure:

<body ng-app="weather" ng-controller="weatherCtrl">
    <h1 class="text-center">Weather</h1>
    <h2 class="text-center">{{city}}, {{country}}</h2>
    <h2 class="text-center">{{temperature}} °C</h2>
</body>

Answer №1

Utilizing promises to chain requests together is the recommended approach,

An additional point to note is that the http component is missing in the second request

Code:

app.controller("weatherCtrl", function ($scope, $http) {

    function infoReq() {
        return $http({
            method: 'Get',
            url: 'http://ipinfo.io/json'
        })
    }

    function weatherReq() {
        var apiKey = "";
        var apiCall = "http://api.openweathermap.org/data/2.5/weather?q=" + $scope.city + "&APPID=" + apiKey;
        return $http({
            method: 'Get',
            url: apiCall,
        })
    }

    $scope.makeRequest = function () {
        infoReq()
            .then(function (response) {
                $scope.city = response.data.city;
                $scope.country = response.data.country;
                return weatherReq();
            })
            .then(function (response) {
                console.log(response.data);
            })


    }

})

Answer №2

const request = {
 method: 'POST',
 url: "http://api.weather.com/data/2.5/info?q=" + $scope.location + "&APIKEY=" + weatherKey;
 headers: {
   'Content-Type': 'application/json'
 },
 data: { example: 'example' }
}

$http(request).then(function(){...}, function(){...});

Utilize the provided http service within your angularjs controller to send the request.

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

Can you explain how parameters are being transferred to the onClick function?

While examining some code, I noticed the following snippet: <temp onClick={this.onSelected} /> The onSelected function appears to be defined like this: onSelected = (id: string) => { [...] } I'm curious how the id: string is being pas ...

What is the mechanism Angular utilizes to determine the exact location of directives within a webpage?

Can you explain how Angular is able to locate the directives on a webpage and establish connections with or observe those elements? I've searched through the DOM reference, but it seems like methods like getElementbySomething and querySelectorAll may ...

I would greatly appreciate any recommendations on how to troubleshoot and

I've been working on the "Map the Debris" challenge at freecodecamp, and I'm facing an issue. While my code works fine in my PC's editor, it doesn't satisfy the conditions when I paste it into the website area. Any suggestions on how t ...

Using AngularJS to make a $http GET call with an array of parameters

Trying to make an $http.get request to my rest service using this code: $http({ method: 'GET', url: '/api/item/all', params: { query: { userid: 7 }, fields: 'title' } }); E ...

Discovering the Vertical Dimension of a Web Page Displayed in a Window

Working with an ASP.NET Site that utilizes a single Master Page, I am facing a challenge on one of the pages where I display a PDF file as the main content. I am looking for a solution to determine the appropriate size for the PDF control so that it fits ...

Check for my variable in the redux state before proceeding

Currently, I am creating connection and registration screens, with a profile button on the bottom tab bar. The objective is for the user to be directed to their profile page if they are logged in (user data stored in Redux), or to a landing screen with log ...

How to toggle between displaying divs using JavaScript and Jquery

How can I use JavaScript to show or hide specific divs on page load and upon clicking different links? I want to display the "houseImages" div by default, while hiding the "landImages", "renovationImages", "UpcomingImages", and "voteForNext" divs. Then, w ...

Using Node http-middleware-proxy and integrating it with Express to communicate with Tomcat server

We have set up our Java application (which is spring based) in a Tomcat container, with the UI modules also running in the same environment. When we access Tomcat directly through http://localhost:8080, a login page is displayed and then a 302 redirect occ ...

Utilizing AngularJS: Implementing a directive to invoke a controller function with parameters

One concept I am already familiar with involves calling a controller function without arguments inside a directive. The following code demonstrates this: Firstly, in the directive definition: scope: { actionFunc: "&" } Within the directive template: ...

Error in Internet Explorer while using Angular: Cannot modify nodeValue of an undefined or null reference

Summary To see the problem in Internet Explorer and the solution, check out this Code Pen. By replacing <div>{{item.name}}</div> with <div>&nbsp;{{item.name}}</div>, the issue is fixed. But why? Detailed Question I'm dea ...

Retrieve the name of the file from a given URL by using JavaScript/jQuery, even when only the directory path is

I need to extract the current filename from the URL using: $currentFile = window.location.pathname.split("/").pop(); This method functions properly when the full path looks like: http://www.yoursite.com/folder/index.php It will return index.php, index. ...

Text area featuring unique border design, with border color change upon focus?

Currently, I have a text area with borders that are designed in a unique way. However, I am looking to change the border color when the user focuses on the text area. Do you have any suggestions on how I can achieve this effect without affecting the curre ...

Tips for personalizing a drop-down menu in AngularJS with the Ionic framework

Being new to AngularJs and the Ionic framework, I am currently working on building a dropdown list component. I have successfully created one using the code below. Here is the HTML structure: <ion-view title="Drop down list"> <ion-content& ...

The eval() function does not run scripts from external sources with a src attribute

Instead of using eval() to execute all <script> tags after completely rewriting a div, I have encountered an issue. The following code snippet works for inline-scripts, but it doesn't have the same effect on external scripts like: <script sr ...

Issue with validating passwords and confirming them accurately

Recently started using AngularJS and encountering an issue with form validation. I have a form that includes fields for username, email, password, and confirm password. Even when all the fields are filled out correctly, the submit button remains disabled ...

Tips for incorporating a loader in AngularJS while binding an HTML table:

Below is the HTML table I have created: <body ng-app> <div class="wrapper wrapper-content" ng-controller="InboxMailCtrl"> <table> <tbody> <tr> ...

JQuery and JavaScript will not function INSIDE an AJAX script

Utilizing an AJAX script, my website dynamically loads content from a separate HTML page "content.html" into my content DIV. The recurring issue I am encountering is that any content containing scripts, such as my slideshow JQuery Plugin or dynamic tabs pl ...

Creating an Angular library that utilizes HTML components from the application

This is my first attempt at developing an angular library. My goal is to create a header and footer library for angular. The challenge lies in making sure that it integrates seamlessly with the HTML structure of the application it is being used in. Below ...

Tips for creating seamless image transitions using a toggle button

My transition effect is working smoothly, but I am having trouble setting it up for the image. How can I resolve this issue? I attempted the following: var lightsOff = document.querySelector("#lights-off"); var lightsOn = document.querySelector("#lights-o ...

What is the correct way to include URL parameters within an AJAX data object?

I'm experiencing a strange issue that I can't seem to solve. My application makes use of AJAX to access JSON data. I am utilizing the platform's built-in parameter support to filter by category and tag. The format that is currently functiona ...