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

Unable to set the cookie when using the fetch API

My node.js server is listening on port 3001. WITHIN THE REACT FILE On the login page component. fetch('http://localhost:3001/api/login',{ method:'POST', headers: { Accept: 'application/json', ...

What Are the Possible Use Cases for Template Engine in Angular 2?

For the development of a large single page application (SPA) with Angular 2.0, I have decided to utilize a template engine like JADE/PUG in order to enhance clarity and clean up the code. My goal is to achieve optimal performance for the application. Th ...

Export a SQLite table with a JSON column without the need for double escaping characters

Consider a SQLite table created as follows: create table t(id, j json); insert into t values (1, '{"name": "bob"}'); insert into t values (2, '{"name": "alice", "age":20, "hobbies": ...

How can I fix the 'Null is not an object' error that occurs while trying to assess the RNRandomBytes.seed function?

Currently, I am in the process of creating a mobile application using expo and react-native. One of the features I am working on involves generating a passphrase for users on a specific screen. To achieve this task, I have integrated the react-native-bip39 ...

Jumping Iframe Anchor Link in Src

I'm facing a challenge with an iframe positioned in the center of a webpage. I want to show content from another page within the iframe, but not starting at the very top. To achieve this, I inserted an anchor into the src of my iframe, linked to an a ...

Alert: VirtualizedList warns of slow updates for a large list despite optimized components

Struggling with avoiding the warning message "VirtualizedList: You have a large list that is slow to update" while utilizing the <FlatList> component in React-Native. Despite thorough research and attempts at finding a solution, including referencin ...

Select the input based on the name and value provided from a radio button using jQuery

I want to show a div element when the user chooses option 4 from a radio button. $(document).ready(function () { $("#GenderInAnotherWay").hide(); $("input[name='Gender'][value=4]").prop("checked", true); $("#GenderInAnotherWay").tog ...

"Combining HTML, PHP, and JavaScript for Dynamic Web

Here is the PHP function that retrieves the visitor's profile image thumbnail: <?php echo voip_profile_image($visitorid,'thumb'); ?> The issue lies in the fact that $visitorid is stored in JavaScript under the sRemoteid parameter. Wi ...

Combining the power of jQuery, PHP, JavaScript, and the popular WordPress platform, let's unlock

After going through numerous attempts to find answers for similar issues, I'm unable to get any of the suggested solutions to work. My WordPress site requires a plugin that utilizes jQuery. The main file for my plugin is located at wp-content/plugins ...

Validating JSON Schema with date fields

I'm running into some challenges while using the JSchemaValidatingReader within the Newtonsoft.Json.Schema library. The problem arises when trying to validate date fields in JSON data. Here is an example of the schema and data being used: var schema ...

Interacting with the header component within the renderHeader property of the MUI Data Grid Pro will update the sortModel

Currently, I am utilizing the Material UI DataGridPro component to construct a React Js application. I am interested in developing a customized filtering feature. In the image below, you can see a red box representing an IconButton for the filtering view ...

Retrieve dashboard configurations in AngularJS by making an $http request prior to initiating the dashboard controller

I am currently immersing myself in Angular and tackling a complex dashboard framework all built with Angular. Prior to loading the controllers, I need to fetch various dashboard settings from the server using $HTTP. These settings play a crucial role in de ...

Pattern matching tool for identifying React components with an unlimited number of properties

Currently diving into MDX and experimenting with Regex to extract details on React components from Markdown files. The regex pattern I'm aiming for should: Detect all types of React components This includes identifying the opening tag <Component ...

Load grid data only when the tab is clicked in ExtJS

Our app features a dynamic grid loaded with multiple tabs, each containing one or more grids. The issue currently is that when the application loads, it automatically calls all the URLs instead of waiting for the user to click on a tab. We want to optimi ...

What is the method for invoking a custom directive's function in AngularJS?

When working with AngularJS, you have the ability to create a button that triggers an action. Here's an example: <div ng-controller="myController"> <button ng-click="onButtonClicked()">Click me</button> </div> Now, let&apos ...

ListView Adapter fails to display Android TimeStamp values

Whenever my ListView refreshes or reloads, the timestamp is consistently showing as Jan 17, 1970. Why does this keep happening? The value of my timestamp 1441339200 = 2015-09-04 Snippet of code for the timestamp CharSequence timeAgo = DateUtils ...

how can I transfer model values to a dashboard in Rails 5?

I have developed an app that includes an adminlte dashboard. The dashboard is populated with various values obtained by a jQuery file. I am trying to pass module values to the dashboard. For example, the number of users shown in the dashboard should be fet ...

Transforming a Java object containing a String JSON field into a JSON format

Within our application, there is a database table that stores results as JSON in the following format: ---------------------------------------------------- ------------- content | other fields... --------------- ...

Focusing on a particular iframe

I am currently using the "Music" theme from Organic Theme on my WordPress site and have inserted this code to prevent SoundCloud and MixCloud oEmbeds from stretching the page width: iframe, embed { height: 100%; width: 100%; } Although the fitvid ...

objects bound to knockout binding effects

I have been struggling to understand why the binding is not working as expected for the ‘(not working binding on click)’ in the HTML section. I have a basic list of Players, and when I click on one of them, the bound name should change at the bottom of ...