What are the steps to utilizing an angular-js $resource?

Struggling to implement the angular-js $resource function in an app built with the ionic framework. Having trouble getting it to work. Relevant code:

Service.js

.factory('Pages', function($resource) {
    var source = $resource("http://localhost:5432/api/pages",{},
    {query: { method: "GET", isArray: false }});
    return source;
})

controllers.js

.controller('PagesCtrl', function($scope, Pages) {
$scope.pages =  Pages.query();
$scope.results = $scope.pages.results;
console.log($scope.results);
})

browse.html

<ion-view view-title="Browse">
  <ion-content>
    <h1>Browser</h1>
    <ion-list>
      <ion-item ng-repeat="page in results">
        <h2>{{page.title}}</h2>
      </ion-item>

    </ion-list>
  </ion-content>
 </ion-view>

and the data

{
"count": 2,
"next": null,
"previous": null,
"results": [
    {
        "id": 1,
        "parent": null,
        "title": "Blog",
        "content": "<p>Blog</p>",
        "content_model": "richtextpage",
        "slug": "blog",
        "publish_date": null,
        "login_required": false,
        "meta_description": "Blog",
        "tags": ""
    },
    {
        "id": 2,
        "parent": null,
        "title": "Lorem Ipsum",
        "content": "Lorem ipsum ....",
        "tags": ""
    }
]
}

Despite efforts, the console log (in controllers.js) consistently shows 'undefined'. Been troubleshooting for hours without success.

Answer №1

When using the .query() method, the result object returned is a promise that will eventually contain the result.

It's important to note that when you attempt to access the result property of your payload, the request may not have finished yet.

Thankfully, Angular's ng-repeat statement has built-in support for promises. In your view file, browse.html, you can simply use:

<ion-item ng-repeat="page in pages.results">

This eliminates the need to handle $scope.results in your controller, resulting in cleaner code overall.

Answer №2

Remember that $scope.pages is a promise object. If you want to log the result to the console, make sure to use a callback function such as this:

$scope.pages = Pages.query();
$scope.pages.$promise.then(function (response) {
  console.log(response);
});

Answer №3

Here is my recommendation for enhancing the service:

.factory('Pages', function($resource) {
    return {
       source: $resource("http://localhost:5432/api/pages",{},
                   { 
                      query: { 
                          method: "GET", 
                          isArray: false 
                      }
                    })
    }
})

Next, in the controller:

.controller('PagesCtrl', function($scope, Pages) {
    $scope.pages =  Pages.source.query();
    $scope.results = $scope.pages;
    console.log($scope.results);
})

It's important to note that the query method only returns an object because we specified to $resource that our query does not return an Array (it is false).

This implementation will only be successful if your Backend is correctly defined.

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

Code timer for HTML redirection

Some time ago, I created this code to display random events on my website. While the code functions well, I now wish to incorporate a timer. I envision that when a user refreshes or enters the page, they will be redirected initially and then redirected ag ...

Measuring the Size of Objects by Key Value

In my JavaScript object, I have an associative array containing different values: var data = [ {val:1, ref:10, rule:100}, {val:1, ref:12, rule:120}, {val:2, ref:13, rule:165}, ]; I am looking to find the length of values based on a specific key (for exam ...

Retrieve the access ID from the conn.query result

When I run a SQL query, I need to extract the primary key (id) of the event returned so I can use it in another SQL query. However, attempting to access it using result.insertId returns null for the event object. Even logging result.insertId only outputs ...

Design a model class containing two arrow functions stored in variables with a default value

I am looking to create a model class with two variables (label and key) that store functions. Each function should take data as an input object. If no specific functions are specified, default functions should be used. The default label function will retur ...

Implementing a delay for adding a class using jQuery

I'm attempting to delay the execution of the addclass function in this plugin, but it's not functioning as expected. I have inserted .delay(14000) just before the .addClass function. Here is the code snippet: if (typeof a.cookieguard.displayMes ...

State initialization issue in a connected React app using Redux

I am facing a challenge with my ReactJs app that utilizes Redux for state management. The state of the application is a complex JSON object with mutable fields. When I initialize the reducers, it is essential to specify the initial state; otherwise, access ...

Missing data: Node JS fails to recognize req.body

I've looked through various posts and I'm feeling quite lost with this issue. When I run console.log(req), the output is as follows: ServerResponse { ... req: IncomingMessage { ... url: '/my-endpoint', method: &a ...

Change the visibility of a div element by leveraging the data-target attribute

Hey there, I have a question about how to use the data-target attribute to set the display of a div. Check out my HTML code below: <div class="page page-current" id="home"> PAGE 1 <a href="#" class="next" data-target="#about">Go to about< ...

Is there a newline and colon in the req.body from the post router?

Can someone help me with extracting the post data from req.body? Here is my post data: { name:'asdf', completed: false, note: 'asdf' } However, when I try to console it using JSON.stringify, req.body ends up looking like this: {" ...

Transmitting a large amount of information via POST or GET requests

I need help with sending an XML file from a textfield in my HTML using AJAX to a PHP file. Below is the PHP code: <?php $data = urldecode($_POST["xml"]); echo $data; ?> The data is sent to the PHP file like this: $("#btn_save").click(fun ...

Contrasting outcomes when tackling a problem in node.js versus python

After tackling a challenging leetCode problem, I successfully came up with the following solution: Given d dice, each with f faces numbered from 1 to f, determine the number of possible ways (modulo 10^9 + 7) to roll the dice so the sum of the face up nu ...

React is giving me trouble as I try to map my tables. I am struggling to figure out how to do this

I have two .CSV files: "1.csv" and "2.csv". I need to display the data from each file in a table using the BootstrapTable component. My async functions, GetData(file) and FetchCSV(file), are working fine and providing the necessary array of objects for the ...

Issue encountered when utilizing html5/js Audio on Safari (Windows)

While working on my HTML5 game, I encountered an issue in Safari where I saw this error in the JavaScript console: "Result of expression 'Audio' [undefined] is not a constructor". To add sound to my game, I am using the following code: var audi ...

Retrieving information from two MongoDB collections (with filtering on _id) within a Meteor application

I've been facing an issue with my Meteor application for quite some time now. I'm creating a platform where users can sign up for groups, upload images, and assign specific tags to their images. The Tags collection holds unique identifiers (_id) ...

`Multiple confirmation modals appearing from delete button in vue-bootstrap`

Trying to find a solution for the issue of having a unique reference to the modal within this loop. I attempted giving the ref a grade.id at the end, but it didn't work with String interpolation and the b-modal ref. I also tried using :ref. Below is ...

Creating a customizable CSS selector in an Angular.js application

I'm currently developing a project in Angular.js involving a plane view where various objects are located. Every time a user drags an item from the left menu bar to the center of the screen, a new object is created. The unique CSS class for each item ...

Attempting to showcase an OpenLayers Map using Vue3 and Nuxt framework

Seeking assistance with integrating OpenLayers map into a Vue3 application component and pulling it into a page. The setup process seems correct, but the map is not rendering, leaving a blank space. I have searched online for solutions, but the lack of err ...

Is it possible to navigate between jQuery EditInPlace fields using the Tab key?

Seeking advice on implementing tab functionality for a page with multiple jquery EditInPlace fields. The goal is to allow users to navigate between fields by pressing the tab key. Currently using the 'jquery-in-place-editor' plugin available at: ...

Tips for setting up data and transferring it to the test document

I am interested in setting up a configuration file to store all input data for my tests. I want the test to read this data from the file while it is being executed. For instance, I would like to specify browser name, search parameter, and server address in ...

Employing the search feature to pinpoint a related value

My goal is to fetch the value of .postingTitle for the specific job record that the user selects to apply for. I am using the code jobTitle = $('.applyButton').parents().find('.postingTitle').val(); to achieve this, but currently, I am ...