logo
down
shadow

How to properly convert controller and service from AngularJS to using ng-resource


How to properly convert controller and service from AngularJS to using ng-resource

By : Joshua
Date : November 28 2020, 09:01 AM
help you fix your problem I agree with @Mark that you probably don't have enough operations in your API to fully take advantage of $resource, so the benefits aren't as great. For what you have now though, if you're wanting to use $resource, I would set it up like this:
code :
angular.module('PostsResources', ['ngResource'])
   .factory('Post', function($resource) {
      return $resource('/posts/:postId', { postId:'@id' }, {
         like: {
            url: '/posts/:postId/like',
            method: 'POST',
            params: { postId:'@id' }
         }
      })
   });
self.posts = Post.query(null, BaseService.errorHandler(self));

self.like = function(post) {
   post.$like(function() {
      angular.forEach(self.posts, function(post, index, obj) {
            if (post.id == id) {
                post.usersVoted.push('voted');
                post.voted=true;
            };
        });
   }, BaseService.errorHandler(self));
};
self.errorHandler = function(viewModel) {
   return function(error) {
      BaseService.accessErrors(error.data);
      viewModel.cerrorMessages = BaseService.cerrorMessages;
   };
};


Share : facebook icon twitter icon
AngularJS : How do I properly set a service property from model data in a controller?

AngularJS : How do I properly set a service property from model data in a controller?


By : Syafiq
Date : March 29 2020, 07:55 AM
I wish this helpful for you This has nothing to do with Angular. It is plain, old JavaScript-related.
In your fiddle's HTML you have (numbers are for reference below):
code :
(1)<input type="text" ng-model="text1">
(2)<button ng-click="saveText(text1)">Save Text</button>
   ...
(3)<input type="text" ng-model="textObj.text1">
(4)<input type="text" ng-model="textObj.text2">
(5)<button ng-click="saveObj(textObj)">Save Object Text</button>
var a = 'value1';
var b = a;
// Now: a === 'value1', b === 'value1'

a = 'value2';
// Now: a === 'value2', b === 'value1'
var a = { key: 'value1' };   // Creates new object, say {obj1}
var b = a;                   // Now b references {obj1} as well
// Now: a.key === 'value1', b.key === 'value1'

a.key = 'value2';   // Changes {obj1}'s key's value
                    // but {obj1} is also referenced by b, so...
// Now: a.key === 'value2', b.key === 'value2'

// This does not happen in your code, so you never lose reference to
// the same object from both `myService.object` and `inScope.textObj`
a = { key: 'value3' };   // Creates new object, say {obj2}
                         // but b still references {obj1}, not {obj2}, so...
// Now: a.key === 'value3', b.key = 'value2'
how to bind variable from controller to service for data property $resource angularjs

how to bind variable from controller to service for data property $resource angularjs


By : Tyler Griffing
Date : March 29 2020, 07:55 AM
I wish did fix the issue. You cant't, at least in this configuration, because custom $resource methods, AFAIK, accept following signature:
code :
action: {method:?, params:?, isArray:?, headers:?, ..}
AngularJS - Controller resource call not passing parameters to service factory?

AngularJS - Controller resource call not passing parameters to service factory?


By : Ivan Bačić
Date : March 29 2020, 07:55 AM
I wish this helpful for you In AngularJS, I'm trying to pass a parameter in a controller call to a service factory. However, I can't seem to get the parameter passed. The function always passes what I set to be the default in the service. And if I don't include the default, it doesn't pass anything. , Try
code :
services.factory('Room', ['$resource',
    function($resource)
        {
            return $resource('/room/:room_id', {}, {
                enter: {method: 'PUT', params:{room_id:'@room_id'}}
        });
    }
]);
Angularjs. Resource has value in service but doesn't return data to controller

Angularjs. Resource has value in service but doesn't return data to controller


By : Paul-Magu
Date : March 29 2020, 07:55 AM
I wish this helpful for you I'm trying to get data from rest service with $resource anda in my service data return has value but when I try to get it in my controller js class this one daesn't has value. And I can't to go into if because I dont have value in my result. , I know why that wasn't working.
code :
'checkAsignaturainProfesor': { 
    method: 'GET',
    url: 'api/asignaturaprofesors/checkAsignaturainProfesor/:asignaturaId/:profesorId',
    transformResponse: function (data){
        ***if (data){
            data = angular.fromJson(data);
        }***
        console.log('service checkAsignaturainProfesor ',data);
        return data;
    'checkAsignaturainProfesor': { 
    method: 'GET',
    url: 'api/asignaturaprofesors/checkAsignaturainProfesor/:asignaturaId/:profesorId',
    transformResponse: function (data){
        console.log('service checkAsignaturainProfesor ',data);
        return data;
AngularJS service call from controller not working properly

AngularJS service call from controller not working properly


By : Stefano Andreotti
Date : March 29 2020, 07:55 AM
To fix this issue console.log() takes a reference to the object specified and immediately runs a (typically background) process to write it to the log. What it writes depends entirely on timing. You run into this a LOT with async calls - if you step through it with a debugger or set a breakpoint, it prints the correct value. If you run it raw, it fails. It's because it's executing before your network request has completed.
Move the console.log inside the success function:
Related Posts Related Posts :
  • Angularjs Replace `#` with `w` or with something else
  • Error while uploading a file with Angular ng file upload
  • angularjs WebAPI authentication project template
  • How to structure ui-router to have SEO friendly url structure
  • Dialog becomes blur after applying animation
  • ui-router State Children and Resolvers
  • Select2 not working in angular
  • Have some generator can gener angular component api document?
  • Is it possible to resend image url received from server back to it as an image after processing
  • When is "onEnter" exactly executed
  • Jasmine how do I set the response of a spy
  • How to use variable from a Controller in a Directive link function?
  • AngularJS - set validity of wrapped directives
  • How to show/hide different data on clicking different links in AngularJS?
  • can i paste text input value on-keyup in angular?
  • ui-view do not bind to controler
  • ng-keyup doesn't execute the expression
  • Angular not found until after it's needed?
  • learning angular, having issues with ng-options
  • Angularjs chat with strange polling
  • AngularJS - Adding controller files triggering uncaught error
  • Using the browser to navigate back in an angularjs app with ui-router?
  • ngResource query, get and save
  • NodeJS on Heroku: Push rejected, failed to compile Node.js app
  • Ionic / Angular JS calling the next page by passing a value into a funciton
  • AngularJS - Passing select list value to function returning undefined
  • Angular JS Material mdMedia seems to be not working
  • directive does not work in the ons-toolbar
  • Making Anglular min/max validation code work for three variables on multiple fields
  • AngularJS: Add attribute, compile directive
  • Run part of controller code every time a page is navigated to in Ionic?
  • angular module: Failed to instantiate module due to
  • AngualrJS - What is a Modal
  • form valid ui-select AngularJs
  • Smart-Table vs. Angular-DataTables
  • angularjs clear backing field when input box hides
  • new google.maps.places.PlacesService throwing error
  • Can't route using angular-ui-router
  • $httpBackend.flush() method throws Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting
  • how print multipage with angularprint?
  • Why is 'this' different things in two different functions?
  • AngularJS - Page loads before scope variable is initialised
  • Angular module for moment-range
  • In AngularJS how do I open download pdf in new Tab on iPad browser using ng-click
  • Angular UI Grid API doesn't work in capturing last cell edit
  • Induce controller UI change from within directive with shared variable
  • Angularjs scope not working
  • AngularJS resource dependencies
  • Cannot inject an Angular ngModel in directive in Kendo Grid
  • In angular js 1.4.7 whether the object property/field name should start with string(number is not allowed)?
  • What are the best practices for consuming ASP.NET Web Api with oAuth in Ionic Framework?
  • Angularjs material dialog not working
  • Angular UI Router: UI Parent controller doesn't update when value changes
  • Print a matrix using angular js
  • unbind $scope param from var angular
  • ng-repeat multile fileds with multiple name like append
  • Get result of rest request instead of response?
  • req.body undefined and express api testing using angular
  • Simple ng-Route not working in ng-View
  • Angular filter for HTML formatting
  • shadow
    Privacy Policy - Terms - Contact Us © animezone.co