Utilize $resource to establish a simple object

I have been searching through various tutorial sites without success.

My goal is to create an Angular app that communicates with my server over REST. I initially used this as a starting point and got it working, but I decided to start from scratch to gain a better understanding of the process. Setting up the REST server was straightforward for me as a PHP developer, but I'm facing some challenges on the Angular side.

To organize my project, I created a simple directory structure using Yeoman:

  • root
  • ------app (contains all Angular code)
  • ------engine (Yii2 framework resides here)

In app/script/app.js, I have the following setup:

'use strict'; // What does this line do exactly?

var app = angular
  .module('gardeshApp', [
    'ngCookies',
    'ngResource',
    'ngSanitize',
    'ngRoute'
  ])
  .config(function ($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl'
      })

      .when('/post/index' , {
            templateUrl: 'views/post/index.html',
            controller : 'PostList'
        })

      .otherwise({
        redirectTo: '/'
      });
  });

For handling data received from the server, I created a Post model in the following manner:

app.factory('Post' , ['$resource'] , function($resource){
    var Post = $resource('http://localhost/testApp/engine/web/post/:id' , {id : '@id'} , {update: {method: 'PUT'}});

    angular.extend(Post.prototype , {

        save: function (values) {
            if (values) {
                angular.extend(this, values);
            }
            if (this.id) {
                return this.$update();
            }
            return this.$save();
        }

    });

});

Additionally, I created a controller to fetch the data:

app
    .controller('PostList', ['$scope', '$http' , '$resource',
    function($scope, $http) {

//     $http.get('http://localhost/testApp/engine/web/post').success(function(data){
//         console.log(data); // this works fine and gets the json ed data
//     });


        var posts = new Post();
        console.log(posts.query());

    }]);

I want to achieve dynamic calls instead of manually using $http.get. However, I'm encountering an error stating that Post is not defined. How can I properly define a Post Object to represent the fetched model?

Answer №1

Here is an example of how you can accomplish this:

app.factory('PostService' , ['$resource'] , function($resource){
    var Post = $resource('http://localhost/testApp/engine/web/post/:id', 
        {
            update: {method: 'PUT'}
        }
    );
    return Post;
});

In addition, you can use the following code snippet:

app.controller('PostListController', ['$scope', '$http' , 'PostService',
    function($scope, $http, PostService) {
        console.log(PostService.query());
    }]);

Remember to always return your constructed object in a factory to enable it for dependency injection later on. Then, in your controller, specify that you need PostService, and Angular will take care of injecting it for you.

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

Typescript raises an issue regarding a React component's optional prop potentially being undefined

I have a basic React component that looks like this: interface ComponentProperties { onClick?: () => void; } const CustomComponent = (properties: ComponentProperties) => { if (!properties.onClick) { return <></>; } ...

Learn how to create dynamic graphs using AngularJS with JSON data outputs

.controller('HomeCtrl', function ($scope, $http, $stateParams, $state, FirstHiveService) { var samplelineJsonData = [ { "month": "Jan", "noOfUs ...

The most efficient method for handling a vast amount of data in NodeJS

My database consists of 4 million numbers and I need to quickly check if a specific number exists in it. Example of the database: [177,219,245,309,348,436,...] I initially tried using a MySQL table for this task, but it took a lengthy 1300ms just to chec ...

Enhance the functionality of the fb:login button by including a new POST parameter

Hey there! I'm facing an issue where the user is automatically logged back into the site when they click on the login with Facebook button, even after logging out. To tackle this, I'm trying to set up a POST method with a classic condition. if ...

Ui-Router enables $promise data to be accessed by child state views without the need for a controller

If a parent route has a controller and a child route doesn't, should the children be able to access $scope data from the parent? .state('parent', { url: '/parent/{idParentRecord}?extraInfo', templateUrl: 'app/parent/paren ...

Having trouble resolving the signature of a class decorator when invoked as an expression with @Injectable in Angular

Error Message: Unable to resolve the signature of a class decorator when called as an expression. The argument type 'ClassDecoratorContext' is not compatible with the parameter type 'string | symbol | undefined'. After creating a book ...

What is the best way to link a button to a form in Angular?

I'm currently utilizing Angular 6.x and I am looking to link a submit button that is located outside of the form in the DOM. Essentially, I want to achieve something similar structurally to this: <button type='submit' form='myform&a ...

What solutions are available for resolving the devServer issue in webpack?

Any help or advice would be greatly appreciated. I have configured webpack and everything works in production mode, but the webpack-dev-server is not recognizing static files and is giving the error "Cannot get /". How can I resolve this issue? Thank you i ...

Are beta versions included in the "latest" versions of package.json?

Within the package.json file, you have the option to define a package to be synchronized with the most recent version: { ..., "devDependencies": { "gulp": "latest", ... }, ... } When "latest" is specified, does it encompass alpha ...

How to prevent page refresh when hitting enter in jQuery form?

Currently, my form does not refresh the page when I click the button to submit it. However, if I press Enter while a text input is selected, the page will refresh. Is there a way to make pressing Enter on the text input perform the same action as clicking ...

Limiting the movement of items to specific divs with dnd-list in javascript/angular

I have been utilizing the 'Drag & Drop List' feature from . Currently, any click and drag action on an <li> element will cause it to move by default. Is there a method to limit this behavior so that the user must click on a specific s ...

Strategies for refining the names in the dropdown options using AngularJS

I am working with a select element that has a name and id as options value. I am also adding '-' along with the name. However, there is a scenario where the name will be empty and in that case, the '-' should not be displayed. The expe ...

Can you tell me the equivalent of this Curl command in Angular JS?

Execute the Curl command with the datavalueset XML file at "", using the Content-Type application/xml and authentication credentials admin:district, while also running in verbose mode. ...

A step-by-step guide on creating a chainable command in Cypress

Imagine having a variable called username. Now, consider a chainable function that needs to verify whether the username is empty or not. Original Method: if(username !== "") { cy.get('#username').type(username) } Expected Outcome: ...

Why is Reactjs converting image files to URL strings when deleting them?

While trying to delete files, I noticed that they are being converted into URL strings. How can I prevent this conversion? If I change return URL.createObjectURL(file); to return file;, the files stay as they are and do not convert to URL strings, but th ...

Exploring the power of for-loops in Reactjs within the componentDidMount lifecycle

I'm struggling to understand why the state of my component fails to update inside a for-loop. Let's look at an example: class Example extends React.Component { constructor() { super() this.state = { labelCounter ...

Trigger a page refresh when you revisit it

Currently, I am utilizing Nuxt in SPA mode and my page structure is set up like this: pages ... - users/ - - index - - new - - update/ - - - _id ... I have a page dedicated to displaying a list of users along with a 'subpage' for adding new u ...

Unable to locate module in Node.js - module.js

I encountered an error while running the node server which states: $ node server.js module.js:339 throw err; ^ Error: Cannot find module './server/routes' at Function.Module._resolveFilename (module.js:337:15) at Function.Module ...

Guide to adding a file upload progress bar to your website

Is there a way to enhance file upload experience on my web application beyond the usual animated gif? I'm currently using .Net, but open to platform agnostic solutions as well. ...

Implementing a 3D cylinder chart with ReactJS using Highcharts

I've been attempting to incorporate a cylinder 3D chart into my react component, but I keep encountering this error message. Error: Highcharts error #17: www.highcharts.com/errors/17/?missingModuleFor=cylinder missingModuleFor: cylinder The code in ...