Incomplete data being returned from Angular $resource request

Could someone please explain why I am encountering the following issue:

I am making a typical API call in my controller using the Angular resource directive.

$scope.weatherAPI = $resource('http://api.openweathermap.org/data/2.5/forecast/daily', {callback: 'JSON_CALLBACK'}, {get: {method: 'JSONP'}});
$scope.weatherResult = $scope.weatherAPI.get({ q: $scope.city, cnt: 4, APPID: 'xxxxxx' });

After receiving the results, I attempt to log them in the console.

console.log($scope.weatherResult);
console.log($scope.weatherResult.city)

console.log("scope weatherResult " + $scope.weatherResult);
console.log("scope weatherResult.list: " + $scope.weatherResult.list);
console.log("scope weatherResult.city: " + $scope.weatherResult.city);

However, despite the objects being present in $scope.weatherResult, when trying to access its properties they show as undefined, preventing me from utilizing that data effectively.

https://i.sstatic.net/YEANa.png

Answer №1

According to the provided documentation:

The important thing to remember is that when you call a method on a $resource object, it immediately returns an empty reference (either an object or an array depending on isArray). The actual data will only be populated into this reference once it is returned from the server.

-- Find more information in AngularJS $resource API Reference

To ensure your function waits for the data to resolve, utilize the .then method of the $promise property of the $resource object and provide a function to the $q service.

$scope.weatherAPI = $resource('http://api.openweathermap.org/data/2.5/forecast/daily', {callback: 'JSON_CALLBACK'}, {get: {method: 'JSONP'}});
$scope.weatherResult = $scope.weatherAPI.get({ q: $scope.city, cnt: 4, APPID: 'xxxxxx' });

$scope.weatherResult.$promise.then(function onFulfilled(data) {
    console.log(data);          
    console.log(data.city);

    console.log("scope weatherResult " + $scope.weatherResult);
    console.log("scope weatherResult.list: " + $scope.weatherResult.list);
    console.log("scope weatherResult.city: " + $scope.weatherResult.city);
});   

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

Filtering nested arrays in Javascript involves iterating through each nested

I have a nested array inside an array of objects in my Angular app that I'm attempting to filter. Here is a snippet of the component code: var teams = [ { name: 'Team1', members: [{ name: 'm1' }, { name: 'm2' }, { name ...

Having trouble with Instafeed JS loading?

I am currently experimenting with instafeed.js, but I am encountering difficulties getting it to load on a basic bootstrap page. While everything else on my page loads successfully, this particular container remains empty without any Instagram code presen ...

Display an additional dropdown menu after the user has made a selection in the first dropdown

Initially, I must address a concern that has previously been resolved; however, the alternative options available on this platform do not meet my needs. Essentially, I aim to create a concise form with two dropdown menus. The first dropdown menu is always ...

Running JavaScript code after an f:ajax response in JSF

Within my JSF 2 web application, I have implemented the following code snippet to manage and update the contents of a rich:dataTable based on the selectedStatus: <h:selectOneRadio id="statusSelection" value="#{backingBean.selectedStatus}" style="width: ...

Adding external JavaScript and jQuery files in Nuxt 3: A step-by-step guide

After successfully adding the CSS files in Nuxt 3 and nuxt.config.ts, everything is working as intended. The next step involves determining the ideal folder to add these script files. Any suggestions on the best approach to solve this issue? ...

Angular 1.4.8 Issue: [$injector:modulerr]

I can't seem to identify the main cause of this error. I consistently see a green underline below the word angular in my javascript file. I'm not sure why. (Using Visual Studio Code) HTML <html ng-app="myapp"> <head> ...

What role does @next/react-dev-overlay serve in development processes?

Currently, I am diving into a NextJs project. Within the next.config.js file, there is this code snippet: const withTM = require('next-transpile-modules')([ 'some package', 'some package', 'emittery', ...

The Javascript alert function always seems to fail to trigger

Below is the complete code I am working with: if( javascript.isGarbage() != true) { alert('I am not garbage!'); } Can someone please explain why this code does not produce an alert message??? ...

Issue with WebRTC, socket.io, and node.js: Unable to access the property 'emit' as it is undefined

Currently, I am in the process of creating a webrtc video app. Within the client code section, the following lines are present: getUserMedia(constraints, handlemedia, errorhandle); constraints = {video: true}; function handlemedia(stream){ //other act ...

Understanding the structure of JSON files without prior knowledge

Without any prior knowledge of the contents, I am seeking to understand the structure of a JSON object. For example, I could receive: [{"x":0,"y":0.4991088274400681,"z":7.489443555361306}, {"x":0,"y":0.7991088274400681,"z":7.489343555361306},{"x":0,"y":0. ...

What is the process for browserifying the net.Socket module in Node.js?

I'm exploring ways to connect and query my MS SQL database from JavaScript in a web browser (specifically Chrome, not IE as I don't want to use ActiveX controls). I came across this Node library called Tedious and Browserify to help with this tas ...

I'm curious to know the distinction between ng-bind and expressions in AngularJS. Can someone shed light on

After searching, I came across this definition regarding the distinction: Typically, ngBind is not used directly. Instead, the double curly markup like {{ expression }} is utilized, which is similar but less wordy. It is recommended to use ngBind over {{ ...

How can I trigger an event in Vue.js when a selection is made in a dropdown menu?

Here is an illustration fiddle: https://jsfiddle.net/40fxcuqd/ Initially, it shows the name "Carl" If I choose Carol, Clara, etc., an event will be triggered and data will be logged to the console. However, if I click on the dropdown and select "Carl" ...

The CE button on the calculator seems to be malfunctioning

My calculator's CE button isn't working as expected – instead of deleting the last entered number, it clears all numbers. I want the CE button to only delete the last number entered. Additionally, I want the calculator to display a default valu ...

Send backspace key press event to the applet and prevent it from continuing

I am struggling with a Java applet on my webpage that allows users to edit text. Whenever a user tries to modify the text by pressing the backspace button, the browser mistakenly forwards to the previous page. I attempted to filter out the backspace key pr ...

Troubleshooting AJAX issues in Firefox with window.location.assign function

Here is my AJAX POST request that sends serialized form data to the server: // Handle form submission. $('#evaluationform').on('submit', function(e){ e.preventDefault(); ajaxObject = { url: $("#evaluationform").attr("a ...

Aggregate and consolidate data based on multiple criteria while ensuring data integrity and maintaining type compliance

In search of a solution, I aim to organize an array of objects by a specified number of keys and calculate the sum of values of another set of keys. For instance, consider the following array: const arr = [ { type: "triangle", color: "green", available ...

The link button appears unselected without a border displayed

I am facing an issue with a link button in my code. Here is the snippet: <div class="col-2"> <a type="button" routerLink="auto-generate-schedules/generate" class="btn btn-primary mb-2">Generate Sche ...

Sliding in and out: toggling multiple divs sequentially using jQuery and a shared class

Having a bit of trouble implementing the slideToggle() function on multiple div hovers, where each hover shows another div within its corresponding container. Here is an example setup: <div class="container">123 <div class="content">ABC< ...

Tips for verifying the presence of a value in a select box

Are there alternative approaches to using a for loop to determine if a value is present in a select box with JavaScript? I am interested in something similar to document.getElementById('selbox').valueExists('myval'); ...