Having trouble accessing JSON response properties within an Angular.js controller

My Angular.js controller is called 'forecastController'.

This is the code for the Angular.js Controller:

weatherApp.controller('forecastController', 
    ['$scope','$routeParams','cityService', 'weatherService', function($scope, $routeParams , cityService, weatherService)
{    
    $scope.city=cityService.city;
    $scope.days=$routeParams.days || '2' ;
    $scope.weatherResult=weatherService.GetWeather($scope.city, $scope.days); //I receive a valid JSON response in the format mentioned below.
    console.log($scope.weatherResult.city.name); //This line is causing an issue
}]);

The JSON object stored in '$scope.weatherResult' is:

{
  "city":     
  {
    "id": 2643743,
    "name": "London",
    "coord": {
      "lon": -0.12574,
      "lat": 51.50853
    },
    "country": "GB",
    "population": 0
  },
  "cod": "200"
}

The service I am using is

weatherApp.service('weatherService', ['$resource',function($resource){
    this.GetWeather=function(city, days){

        var weatherAPI=$resource("http://api.openweathermap.org/data/2.5/forecast/daily?APPID={{MY_API_KEY_GOES_HERE}}",{
        callback:"JSON_CALLBACK"}, {get:{method:"JSONP"}});

        return weatherAPI.get({q:city, cnt:days});     
    };
}]);

The 'forecastController' successfully receives a valid $scope.weatherResult. It can access the properties of the weatherResult JSON object in the HTML view. However, when trying to log it using console.log within the 'forecastController', I get an undefined value. The JSON data is retrieved from

The error message I encounter is:

TypeError: Cannot read property 'name' of undefined
    at new <anonymous> (http://127.0.0.1:50926/controllers.js:19:42)
    at e (https://code.angularjs.org/1.3.0-rc.2/angular.min.js:36:215)
    at Object.instantiate (https://code.angularjs.org/1.3.0-rc.2/angular.min.js:36:344)
    at https://code.angularjs.org/1.3.0-rc.2/angular.min.js:72:460
    at link (https://code.angularjs.org/1.3.0-rc.2/angular-route.min.js:7:268)
    at Fc (https://code.angularjs.org/1.3.0-rc.2/angular.min.js:68:47)
    at K (https://code.angularjs.org/1.3.0-rc.2/angular.min.js:57:259)
    at g (https://code.angularjs.org/1.3.0-rc.2/angular.min.js:49:491)
    at https://code.angularjs.org/1.3.0-rc.2/angular.min.js:49:99
    at https://code.angularjs.org/1.3.0-rc.2/angular.min.js:50:474 <div ng-view="" class="ng-scope">

Answer №1

It is highly probable that your weatherService.GetWeather service method returns a promise. Until this promise is fulfilled, the properties within your $scope.weatherResult object will remain undefined. To handle this situation, utilize the promise's then method:

$scope.weatherResult = weatherService.GetWeather($scope.city, $scope.days);
$scope.weatherResult.$promise.then(function() {
    console.log($scope.weatherResult.city.name);
});

Update: Following my previous comment, it appears that the service is providing a $resource object, which includes a $promise property.

Link To Codepen

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

Creating an Observable Collection in Angular using AngularFire2 Firestore

I am currently using material 2 and attempting to develop data tables with pagination and sorting. In order to achieve this, I require my collections to be observable. However, I believe that I might be incorrectly populating or initializing the arrays in ...

In Javascript, comparing a regular array value with an array value created by the match function

I'm experiencing a problem with comparing values in two different arrays. Here is the code snippet: tagNames = []; tagNames.push('61'); cmt_wrds = '‏‏61'.replace(/[`~!@#$%^&*()_|+\-=?;:&apos ...

Take care of all default document types in the Html5ModeFeature plugin for ServiceStack

This snippet of code represents my first attempt at creating a ServiceStack plugin to support the angularjs configuration $locationProvider.html5Mode(true); when using ServiceStack in a self-hosted environment. This was a requested feature on Stack Overflo ...

Please ensure that the table is empty before reloading data into it

I am facing an issue while binding data from the database. The data is being bound every 5 seconds, however, it does not clear the previous data and keeps accumulating. Instead of displaying just 3 rows when there are 3 in the database, it adds 3 rows ev ...

"Encountering an issue with Material UI where the Theme Style typography is not

Trying to update typography in the theme using Material UI but facing issues with object changes not working. The palette, however, is functioning correctly. Attempts were made to modify H3 styles and default font size but without success. On the contrar ...

Configuring CORS settings in Angular-cli

Upon making a request to my backend url http://docker-users:5500/users?all=true, which returns a list of users, I encountered an issue with Angular-CLI's localhost url: http://localhost:4200. Even after configuring the proxy.config.json file and addin ...

PHP code to export data to a CSV file containing Chinese characters

I attempted the following: $name = iconv("utf-8", "GB18030", $value["name"]); Opening in a text editor and changing the encoding Importing into Excel while adjusting the encoding This process involves PHP and JavaScript: Here is my PHP code: echo & ...

Converting XML data (in SOAP format) to a JSON object using JavaScript

Can AJAX be used to send cross-site requests with a SOAP request and receive an XML response? Additionally, is there a framework similar to Mustache that can easily convert the XML response to JSON format? ...

tips for implementing JSON loading in Ext JS

While attempting to load values from a web service, I encountered the following error message: "ChatStore.data.items[i] is undefined." The mapping code for extjs is as follows: ChatStore = new Ext.data.JsonStore({ storeId: 'ChatStore1' ...

Issue with AngularJS: Component controller fails to load upon routing using ngRoute

As a newcomer to AngularJS, I am struggling with the following code snippet: This is the component defined in the JavaScript file provided: angular.module('EasyDocsUBBApp') .component('loginTag', { templateUrl: 'login ...

The issue I am facing is that the string parameter is not functioning properly within

When creating a new build, I include a parameterized string called VERSION. Within the build, this command is present: sed -i -e 's/REPLACE_ME/$VERSION/g' config/config.json The configuration file in JSON format appears as follows: { "ENV": { ...

A guide on accessing the JSON file data using jQuery

Currently, I am attempting to retrieve data from an API. Essentially, there is a URL that returns JSON data which I need to utilize. var url = "http://212.18.63.135:9034/played?sid=1&type=json"; $.getJSON(url, function(data) { console.log(data) ...

Axios in Laravel fails to recognize JSON data structures

I'm making an ajax request using axios and including the following headers: window.axios.defaults.headers.common = { 'X-CSRF-TOKEN': window.Laravel.csrfToken, 'X-Requested-With': 'XMLHttpRequest', 'Conte ...

PHP, CURL, JSON, AJAX, and HTML - unable to fetch the required data

I am faced with the challenge of transferring data from server 2 to server 1, filling up a form, and submitting it without redirecting the user to server 1. Once the form is submitted, I need the PHP script on server 1 to be executed and send back the resu ...

Transform the arrays, both outer and inner, using jq

I'm facing a challenge that I thought would be simple. I have a json file, and my goal is to extract specific information from it while maintaining the structure. However, I seem to be missing a key insight or "ah-ha moment" in this process. Here&apo ...

Utilize jQuery to automatically assign numbers to <h1-h6> headings

Looking to develop a JavaScript function that can automatically number headings (h1- h6) for multiple projects without relying on CSS. Currently achieving this with CSS: body { counter-reset: h1; } h1 { counter-reset: h2; } h2 { counter-reset: h3; } ... T ...

Adjusting the position of the parent div by manipulating the bottom property

Is there a way to toggle the bottom property of a div when clicking its child anchor tag? <div class="nav" :class="{ 'full-width': isFullWidth }"> <a class="toggle-button" @click="toggleNav"><i class="fa fa-angle-down">< ...

Error message received from Express middleware: "Unable to modify headers after they have been sent."

I have created middleware for my Node Express app to perform the following tasks: Checking all incoming requests to determine if they are from a bot Allowing requests for raw resources to proceed Serving an HTML snapshot if the request is from a bot How ...

Navigating through multiple pages with React Native stack navigation

I'm currently in the process of developing a react native app and I'm facing some confusion with regards to page navigation. It appears that there is a glitch in the navigation flow, causing it to skip a page. <NavigationContainer> ...

Guide to changing the class of a particular child element when the parent element is clicked with vanilla JavaScript

Upon clicking the parent button, a class within its child element will toggle to show or hide. If the child element is selected, a loading animation will appear for a brief moment before reverting back to its original hidden state. I attempted to achieve ...