Fetching JSON data from an external URL using AngularJS

Check out this URL that shows JSON data in the browser:

I attempted to store the data in a variable with the following code:

$http.get('http://api.geosvc.com/rest/US/84606/nearby?apikey=4ff687893a7b468cb520b3c4e967c4da&d=20&pt=PostalCode&format=json').then(function(response) {
            $scope.zipCodes = response;
          });

Here is the HTML where I tried to display it:

<pre>zipCodes {{zipCodes | json}}</pre>

However, nothing seems to be displayed. Any suggestions on what could be going wrong?

I also experimented with this approach:

$http.jsonp('http://api.geosvc.com/rest/US/84606/nearby?apikey=4ff687893a7b468cb520b3c4e967c4da&d=20&pt=PostalCode&format=json').then(function(response) {
                $scope.zipCodes = response;
              });

Furthermore, I attempted to use AngularJS resource but it's giving me an undefined result:

var zipCodes = $resource("http://api.geosvc.com/rest/US/84606/nearby?apikey=4ff687893a7b468cb520b3c4e967c4da&d=20&pt=PostalCode&format=json",
            { callback: "JSON_CALLBACK" },
            { get: { method: "JSONP" }}
            );
        zipCodes.get({}, function(zipCode){
            console.debug(zipCode.PostalCode);
        });
        console.debug(zipCodes.get());
        $scope.zipCodes = zipCodes.get().results;

Answer №1

Ensure to utilize response.data when using the .then method, as it contains four parameters within the response object - specifically data, status, headers, and config

$scope.zipCodes = response.data;

Another Option

An alternative approach is to utilize either the success or error function

$http.get('http://api.geosvc.com/rest/US/84606/nearby?apikey=485a35b6b9544134b70af52867292071&d=20&pt=PostalCode&format=json')
.success(function(data, status, headers, config) {
     $scope.zipCodes = data;
})
.error(function(error, status, headers, config) {
     console.log(status);
     console.log("Error occurred");
});

Answer №2

Why is the filter json included there? When you visit the URL, you will receive an array of elements. Give it a try by printing:

<pre>zipCodes {{zipCodes}}</pre>

After that, if you want to display anything else, you can iterate over it using ng-repeat and customize the display as required.

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

How can I prevent writeFileSync from replacing existing data?

When I use this line of code, it deletes all existing data. Is there a method or function that will append the new data on a new line instead? fs.writeFileSync(path.resolve(__dirname, 'quotes.json'), JSON.stringify(quotey)); ...

Streamline SQL row_to_json with an inner connection

We have a database table named Things, and each instance is associated with another table called Projects through the project_id field. When querying an entry from the Things table, we retrieve a JSON representation of the parent Project record as a value ...

Is there a way to preserve all the downloaded node modules in the package.json file?

Is there a way to keep track of all the node modules installed in package.json without the need for reinstalling them? I've heard about running npm init --yes, but I'm not entirely convinced if that will do the trick. Any assistance on this mat ...

Responsive Tabs with Material-UI

Can MUI's Tabs be made responsive? This is what I currently have: https://i.stack.imgur.com/KF8eO.png And this is what I aim to accomplish: https://i.stack.imgur.com/b3QLc.png ...

How to correctly structure a JSON object in Swift 3

I'm encountering a problem with formatting my JSON object on my Node.js server. My API is configured to accept a JSON object and save it in a database. Everything works fine when I send a POST request using Postman, but I run into an unusual error whe ...

XMLHttpRequest problem: receiving status code 0 from both local and live server

I'm struggling to make this XMLHttpRequest work correctly. This is my first time using AJAX, so I'm not sure if I've formatted everything properly. I've searched all over the internet and found similar information and examples, but cert ...

Converting a PowerShell array to JSON using the ConvertTo-Json function: A Step-by-Step Guide

Observe: C:\> [array]@(1,2) | ConvertTo-Json [ 1, 2 ] C:\> [array]@(1) | ConvertTo-Json 1 C:\> [array]@() | ConvertTo-Json C:\> (I'm expecting [1] and [] from the last two cases respectively) Given this scena ...

Receiving Server Emissions in Vue/Vuex with Websockets

In my Vue component, I was using socket.io-client for WebSocket communication. Now that I've added Vuex to the project, I declared a Websocket like this: Vue.use(new VueSocketIO({ debug: true, connection: 'http://192.168.0.38:5000', })) ...

In what scenarios is it more suitable to utilize style over the sx prop in Material-UI?

When it comes to MUI components, the style and sx prop serve similar purposes. While the sx prop provides some shorthand syntaxes and access to the theme object, they essentially function the same way. So, when should you opt for one over the other? ...

Tallying the number of words delimited by a comma

Here is how my counter function is structured: function count() { var value = ids.val(); return (value == '') ? 0 : value.replace(/\s,?|,$/g, '').split(',').length; } After checking the returned value, data is ...

How can you efficiently cache a component fetching data from an API periodically in React?

I have a situation where I need to continuously fetch data from an API at intervals because of API limitations. However, I only want to update the state of my component if the API response is different from the previous one. This component serves as the m ...

What is the best way to use Python and Selenium to click on an angularjs link by comparing it to the text entered by the user?

A user can input a specific link that they would like to click. For example, if the user inputs "Tampa Bay Downs" for the variable track. In my Python Selenium test program, I will search for the following code: <a ng-click="updateFavorite()(raceInfo. ...

Tips for including an external .js file in a .php file

In an attempt to call a JavaScript function located in an external file, I am facing some issues. Here is my folder structure: C:\xampp\htdocs\test\index.php C:\xampp\htdocs\test\js\functions.js index.php &l ...

Is there a more efficient method for handling this JSON dataset?

After delving into Sitepoint's "Novice to Ninja" and starting to explore jQuery, I can't help but question if there is a more efficient way to write the code I've put together. The resounding answer appears to be "yes." All these cumbersome ...

Divide a JSON API object into segments within an express application

One way I'd like to organize my API's output is by splitting it into multiple pages. My idea is to access them using URLs like this: http://127.0.0.1:3000/api/articles/0/<API-TOKEN> This specific URL would display the first page containing ...

Currently, my nextjs project is up and running smoothly in vscode. When I execute `npm run dev` in the terminal, everything seems to be working fine. However

Whenever I run npm run dev in my terminal to start a nextJS project, it shows the following output: > [email protected] dev > next dev ready - started server on 0.0.0.0:3000, url: http://localhost:3000 but when I try to access it in the browser, ...

Effective methods for transferring parameters between two separate JavaScript files within an express.js application

Currently, I am working with Express.js and facing a challenge in passing parameters from one JavaScript file to another. How can this be accomplished? The two files involved are 1. process.js var WebPageTest = require('webpagetest'); var wpt ...

Nested JSON file retrieval by Axios

I am having trouble retrieving the 'title' from my JSON file. I have been trying to access it through the 'results - metaData' path, but so far without success. The 'resultPacket' is returning data, but accessing 'metaDat ...

What is the best way to manage a vuex dispatch response?

Despite feeling like the answer is right in front of me, I'm waving the white flag and seeking suggestions. The challenge lies in my login form that submits to an AWS API and reacts to the result. The trouble starts when the handleSubmit method is tr ...

What is the best way to generate a random item when a button is clicked?

I'm currently working on a feature in my component that generates a random item each time I access the designated page. While the functionality is set to automatically refresh and showcase a new random item, I am now looking to trigger this action man ...