What methods can I employ within an AngularJS controller to retrieve data from Google App Engine instead of solely relying on a JSON file?

As a newcomer to web development, I have been experimenting with retrieving data from a Google App Engine datastore and selectively displaying it on a webpage using AngularJS. While I have successfully integrated Angular with a JSON file and posted the content of my app engine database using inline JavaScript in an HTML file, I desire to accomplish the same using AngularJS. The resource I attempted to follow, this page, seems to lack crucial information, particularly on where to include the line "gapi.client.guestbook.messages.insert(message).execute();". To build the API and write the new entity, I utilized objectify for annotation and Java.

For instance, the code provided below that references a JSON file within my program functions correctly:

listingControllers.controller('ViewItemsCtrl', [
                '$scope',
                '$routeParams',
                '$http',
                function($scope, $routeParams, $http) {
                    $http.get('phones/' + $routeParams.phoneId + '.json').success(
                            function(data) {
                                $scope.phone = data;
                                $scope.mainImageUrl = data.images[0];
                            });

                    $scope.setImage = function(imageUrl) {
                        $scope.mainImageUrl = imageUrl;
                    }
                    $('.dropdown-toggle').dropdown();
                } ]);

However, when attempting to create a controller to reference the Google datastore, I find myself uncertain about the necessary steps. My best guess, based on my research, led me to the following code snippet which unfortunately does not establish a connection to the database. Typically, when making a simple call to the app engine without Angular, I would begin by invoking the function init(), which loads gapi and calls getListings and insertListings. Should I implement this within the controller? Below is my code, inspired by this.

listingControllers.controller('datastoreTestCtrl', [
                    '$scope',
                    '$routeParams',
                    '$http',
                    function datastoreTestCtrl($scope) {
                      $scope.insertListing = function() {
                        message = {
                          "title" : $scope.title,
                          "price" : $scope.price
                        };
                      gapi.client.listingserviceapi.insertListing(message).execute()    
                      }

                    $scope.list = function() {
                        gapi.client.listingserviceapi.getListings().execute(function(resp) {
                        $scope.messages = resp.items;
                        $scope.$apply();
                      });
                    }
                      }
                    ]);

Lastly, the following code demonstrates the inline JavaScript that I successfully employed to retrieve and insert data into the datastore. While I achieved success in uploading new data, I encountered challenges in utilizing the inserted data on subsequent pages. I would greatly appreciate any insights on how to achieve this or further clarification on the introductory material provided on the Google web apps page. Thank you.

<script type="text/javascript">
        function init() {
                gapi.client.load('listingserviceapi', 'v1', null, 'https://molt-team-233.appspot.com/_ah/api');

                document.getElementById('getListings').onclick = function() {
                    getListings();
                  }
                  document.getElementById('insertListing').onclick = function() {
insertListing(); 
}
        }

        function getListings() {
                gapi.client.listingserviceapi.getListings().execute(function(resp) {
                        if (!resp.code) {
                                resp.items = resp.items || [];
                                var result = "";
                                for (var i=0;i<resp.items.length;i++) {
                                        result = result+ resp.items[i].title + "..." + "<b>" + resp.items[i].description + "</b>" + "[" + resp.items[i].price + "]" + "<br/>";
                                }
                                document.getElementById('getListingsResult').innerHTML = result;
                        }
                });
        }

function insertListing() {
var _title = document.getElementById('title').value;
var _price = document.getElementById('price').value;

var requestData = {};
requestData.title = _title;
requestData.price = _price;

gapi.client.listingserviceapi.insertListing(requestData).execute(function(resp) {
if (!resp.code) {
console.log(resp.id + ":" + resp.author + ":" + resp.message);
}
});
}

    </script>
<script src="https://apis.google.com/js/client.js?onload=init"></script>

Answer №1

From an Angular perspective, whether your data is coming from JSON or a datastore doesn't make a difference in your code. The real distinction lies in your server-side implementation: you'll need to create a function in your GAE application that handles requests, retrieves data from the datastore, constructs a JSON object, and sends it back.

The tutorial you mentioned aims to simplify this process by utilizing GAE Cloud Endpoints. However, setting up these endpoints still requires significant server-side configuration and may not be necessary if your goal is simply to return JSON data.

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

Instantly display selected image

I have encountered some challenges with my previous question on Stack Overflow as I couldn't find a suitable solution. Therefore, I decided to explore an alternative method for uploading images. My current goal is to upload an image immediately after ...

The integration of signalR with jquery mobile is posing several challenges

Recently, I started working with jquery mobile and signalR to implement a calling feature in my mobile app. However, I encountered an error that looks like this: http://localhost:2286/signalr/negotiate?clientProtocol=1.5&connectionData=%5B%7B%22name%2 ...

What could be causing my code to become unresponsive when using a for loop compared to a loop with a specific

After spending a solid 4 hours on it, I finally managed to figure it out. There were no errors popping up, so I resorted to using the debug feature which unfortunately didn't provide much insight. Without any error messages to guide me, I wasn't ...

Displaying the contents of a local HTML file in a div

I am attempting to load a local HTML file into a div, however it is not displaying any content on the page despite showing an alert. Here is the HTML code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> ...

Tips for adjusting the header color in materialize framework?

I've been working on a web template and I'm looking to customize the color displayed in the Android browser (maybe using JS?). The default color is blue. How can I go about changing it? https://i.sstatic.net/RxLbS.jpg Appreciate any help! ...

The git clone operation encounters a problem with the error message: unable to connect, connection refused on localhost port 80

Currently for my project, I'm utilizing isomorphic-git. However, when I try to implement the git.clone function, I encounter the error message Error: connect ECONNREFUSED 127.0.0.1:80. To provide an example of what I am attempting to achieve: import ...

CORS request results in unsuccessful cookie setting in browsers except for Firefox where Set-Cookie header is detected; notably, Chrome does not show the header

I'm experiencing an issue with setting cookies from a NodeJS server to the client using JQuery and AJAX. Despite seeing the Set-Cookie headers in the response, the cookies are not showing up in the document.cookie string. I would greatly appreciate it ...

I am hoping for the outcome to be directed to the homepage

I'm struggling to figure this out, as I am new to classic ASP and JavaScript. I hope someone can help me understand. I want to display the response.write on the main.asp (or the result) page, but each time I try, it redirects to pass.asp on a differen ...

What is the proper way to link an image in a nuxt project?

I am working on a modal in the app.html file of my Nuxt project that prompts Internet Explorer users to switch to another browser. The modal includes links to three different browsers for download. Although the modal is displaying correctly, I keep encount ...

Retrieving a result from a function call is a fundamental aspect of programming

I have a scenario where I am initiating a call from a controller within AngularJS. This call passes some data to a service in order to receive a response that needs to be conditionally checked. Controller patents.forEach(function(item){ // The "patents" ...

Console displaying message of comfort twice - ReactJS

I have a simple app that increments the count from 10 to 11 in the componentDidMount life cycle, but for some reason, the numbers 10 and 11 are appearing twice in the console. I would like to understand why this is happening. Here is the code snippet: im ...

Execute a function upon the selection of an option in AngularJS

My checkboxes are currently updating the total cost by adding and subtracting their respective costs. How can I make my select field do the same? It seems to be defaulting to 7700.00 when the select field is added, while it should be at 0.00 without it. Ad ...

Is it possible for a memory leak to occur in node.js when using new Date()?

For this particular case, when updating an existing MongoDB document with new Date() causing a potential memory leak is a question that arises. One might wonder if allocating a new object with the new keyword necessitates manual deallocation to prevent lea ...

Having difficulty implementing DragControls

My experience with three.js is at a beginner level, and I recently attempted to incorporate a feature allowing the dragging of a 3D model. During this process, I encountered DragControl but faced difficulty implementing it in my code. Upon using new DragCo ...

Error: Encountering difficulty locating the necessary stylesheet for import during the construction of an Angular15 build, while also utilizing Kendo UI

Following the update to Angular 15, I encountered an error while using Kendo UI for the UI controls. It appears that the use of the tilde key is now deprecated. ./src/styles.scss - Error: Module build failed (from ./node_modules/sass-loader/dist/cjs.js): S ...

Fetching a collection from Cloud Firestore using Angular and Firebase

I'm looking to figure out how to retrieve lists from cloud firestore. Here is how I upload a list : export interface Data { name: string; address: string; address2: string; pscode: string; ccode: string; name2: string; } constructor(pri ...

The Angular routes are not displaying correctly within the ng-view

I've been searching for a solution for my first post but can't seem to find one. The content from routing is not displaying in ng-view. index.html <html lang="en" ng-app="myApp"> <head> <script src="//ajax.googleapis.com/ajax/ ...

Struggling to combine select dropdown choices in one calculation

​​I'm currently working on a project where I need to create a website that multiplies three numbers selected from dropdown menus together. However, when I attempt to perform the calculation, I only get the result "1" displayed. I've spent sev ...

What is the process for a webpage to save modifications made by JavaScript?

I am working on a simple web page with a form that contains checkboxes representing items from a database. When the submit button is clicked, these items may be retrieved. Additionally, there is an option to add a new item at the bottom of the page. My go ...

Why does this switch case statement fail to effectively replace the elements of the text in order to unravel this JavaScript problem?

Question I need help converting special characters to HTML entities in a string: &, <, >, " (double quote), and ' (apostrophe). My Code function convertHTML(str) { let tempArr = ['a']; let newArr = []; let regex ...