AngularJS, $resource, get the object from .query() - javascript

Need get one object from .query(), service:
angular.
module('core.users').
factory('User', ['$resource',
function($resource) {
return $resource('users/users.json', {}, {
query: {
method: 'GET',
isArray: true
}
});
}
]);
component:
'use strict';
angular.
module('userDetail').
component('userDetail', {
templateUrl: 'user-detail/user-detail.template.html',
controller: ['$routeParams', 'User', '$filter',
function TaskDetailController ($routeParams, User, $filter) {
var vm = this;
vm.id = parseInt($routeParams["id"], 10);
vm.users = User.query(function() {
vm.user = $filter('currentUser')(vm.users, vm.id);
});
}
],
controllerAs: 'vm'
});
need to get one object from array, 'currentUser', with $routeParams id, problem - vm.user is undefined in controller scope, here
vm.users = User.query(function() {
vm.user = $filter('currentUser')(vm.users, vm.id); // all ok, i got the object
});
console.log(vm.user) // undefined
it's ok for view, i can display properties, but need make .put() request to server with this solo object, when some of user props changed...

From https://docs.angularjs.org/api/ngResource/service/$resource
HTTP GET "class" actions: Resource.action([parameters], [success],
[error])
You should write:
vm.users = User.query();
vm.users.$promise.then(function(response){
vm.user = $filter('currentUser')(vm.users, vm.id);
console.log(vm.user); // Should log the desired result
});
console.log(vm.user); //This will be undefined since it is called before the promise is resolved

You need to declare vm.user
first and put watch on it.
JS :
vm.user = {};
$scope.$watch(function() {
return vm.user;
}, function(newVal, oldVal) {
console.log(newVal); //you can get new value here which is single object
})
vm.users = User.query(function() {
vm.user = $filter('currentUser')(vm.users, vm.id); // all ok, i got the object
});

Related

Can't resolve variables from ui-router resolve object into controller

I'm using ui-router in my app.
app.config(['$stateProvider', function($stateProvider){
$stateProvide.state('State1', {
url:'/State1',
resolve: {
data: function(Service){
return Service.init();
}
},
views: {
"header": {
templateUrl: 'views/header.tpl.html'
},
"center":{
templateUrl: 'views/center.tpl.html'
},
"footer": {
templateUrl: 'views/footer.tpl.html'
}
}
}
})
}
]);
I tried to load a json file from the server and resolve it in the router.
In the resolve object, I call to my service that is responsible for returning promise.
Service.js:
app.service("Service", ['$rootscope', '$http', function($rootscope, $http){
var promise;
this.init = function(){
promise = this.loadData();
return promise;
};
this.loadData = function(){
var url = "users/getData/json.json";
return $http.get(url).then(function(response){
return response.data;
}, function(error){
alert(error);
})
};
}])
center.tpl.html:
<aside id="first-item" ng-controller="FirstController as firstController">
<first-directive>
</aside>
<aside id="second-item" ng-controller="SecondController as secondController">
<second-directive>
</aside>
This is the controller to which I would like to get the resolved data.
FirstController.js:
app.controller('FirstController', ['$scope', 'data', function($scope, data){
this.myData = data;
}]);
I got the next error: Unknown provider: dataProvider < - data. Why?
since promise is never resolved before returning. try this one.
app.service("Service", ['$rootscope', '$http', function($rootscope, $http){
var promise;
this.init = function(){
return this.loadData();
};
this.loadData = function(){
var url = "users/getData/json.json";
return $http.get(url).then(function(response){
return response.data;
}, function(error){
alert(error);
})
};
}])
From the ui-router docs:
// The controller waits for every one of the above items to be
// completely resolved before instantiation. For example, the
// controller will not instantiate until promiseObj's promise has
// been resolved. Then those objects are injected into the controller
// and available for use.
It is cleared that the resolved variables will only be available in the controllers defined in the state config. You can not resolve those variables in a normal controller and you are trying to use data from your state config in your controller and hence you are getting that error.
But, to get those data in your FirstController, you can do like this:
app.config('$stateProvider', ['$rootScope', function ($stateProvider) {
$stateProvide.state('State1', {
url: '/State1',
resolve: {
data: function (Service) {
var data = Service.init();
$rootScope.$broadcast("dataReceivedFoo", {data: data});
return data;
}
},
views: {
"header": {
templateUrl: 'views/header.tpl.html'
},
"center": {
templateUrl: 'views/center.tpl.html'
},
"footer": {
templateUrl: 'views/footer.tpl.html'
}
}
})
}]);
And, then read in your controller:
app.controller('FirstController', ['$scope' function($scope){
$scope.$on("dataReceivedFoo", function(response) {
$scope.myData = response.data;
})
}]);
Basically, we are broadcasting the data from your state configuration and then receiving in your FirstController.
I think adding controller: 'FirstController' line to state will solve the problem.
app.config(['$stateProvider', function($stateProvider){
$stateProvide.state('State1', {
url:'/State1',
controller: 'FirstController',
resolve: {
data: function(Service){
return Service.init();
}
},
views: {
"header": {
templateUrl: 'views/header.tpl.html'
},
"center":{
templateUrl: 'views/center.tpl.html'
},
"footer": {
templateUrl: 'views/footer.tpl.html'
}
}
}
})
}
]);
Resolve
You can use resolve to provide your controller with content or data
that is custom to the state. resolve is an optional map of
dependencies which should be injected into the controller.
If any of these dependencies are promises, they will be resolved and
converted to a value before the controller is instantiated and the
$stateChangeSuccess event is fired.
The resolve property is a map object. The map object contains
key/value pairs of:
key – {string}: a name of a dependency to be injected into the
controller.
factory - {string|function}: If string, then it is an
alias for a service. Otherwise if function, then it is injected and
the return value is treated as the dependency. If the result is a
promise, it is resolved before the controller is instantiated and its
value is injected into the controller.
https://github.com/angular-ui/ui-router/wiki

ui-sref blocked from accessing controller data or view

I am having some trouble getting to the controller for my state param. I am using the correct state to link to the next view.
<td><a ui-sref="orders({customerId: cust.id})">View Orders</a></td>
In my config file I am referencing the state that name and the route params. I commented out the resolve object for now. My goal is to get into the controller then pass the correct data. Notice that I am using controllerAs
My initial thought was ({customerId: ctrl.cust.id }) However that did not change the url route.
The url is changing to match the url name but is not connecting to the controller and is not giving me the view.
(function() {
'use strict';
angular
.module('app.orders')
.config(config);
function config($stateProvider) {
$stateProvider
.state('orders',{
// params: {customerid: null},
url:'/customers:customerId',
templateUrl: './components/orders/orders.html',
controller: 'OrdersController',
controllerAs: 'ctrl',
resolve: {
customerFactory: 'customerFactory',
customerInfo: function( customerFactory, $stateParams) {
return customerFactory.getCustomers($stateParams.id);
}
}
************** my main problem is the resolve. This is blocking me from getting into the next controller. *****************
resolve: {
customerId:[ '$stateParams','customerFactory', function( $stateParams, customerFactory) {
return customerFactory.getCustomers($stateParams.id);
}]
}
})
};
})();
For now my controller is very small. I just want to connect to it. I have checked my networks tab and see GET for the files.
(function() {
// 'use strict';
angular
.module('app.orders')
.controller('OrdersController', OrdersController);
function OrdersController($stateParams) {
console.log('in');
var vm = this;
vm.title = "Customer Orders";
vm.customer = null;
}
}());
I have referenced my module in the main javascript file.
(function () {
'use strict';
angular.module('app', ['app.services',
'app.customers',
'app.orders','ui.router']);
})();
When I comment out the resolve I am able to access the controller. So I know the problem is in the resolve. Here is my service. I am making a request to a Json file with $http request and using .then
Updates Here is my refactored service call I am getting back the correct customer in the console each time.
(function() {
angular
.module('app.services',[])
.constant('_', window._)
.factory('customersFactory', customersFactory);
function customersFactory($http, $log) {
return {
getCustomers: getCustomers,
getCustomer: getCustomer
};
function getCustomers(){
return $http.get('./Services/customers.json',{catch: true})
.then(getCustomerListComplete)
.catch(getCustomerListFailed);
function getCustomerListComplete(response) {
console.log('response.data',response.data);
return response.data;
}
function getCustomerListFailed(error) {
console.log('error', error);
}
}
function getCustomer(id) {
var url = './Services/customers.json';
return $http.get(url, {
catch: true
})
.then(function(response) {
console.log('promise id',id);
var data = response.data;
for(var i =0, len=data.length;i<len;i++) {
console.log('data[i].id',data[i].id);
if(data[i].id === parseInt(id)) {
console.log('data[i]', data[i]);
return data[i];
}
}
})
}
}
}());
There is a working example with your code
It is very hard to guess what is wrong. Based on suggestion I gave you here Have a expression error in ui-sref ... your code seems to be completely valid.
I placed your stuff into this app.orders.js file (the ONLY change is templateUrl path, just for plunker purposes):
angular
.module('app.orders', ['ui.router'])
'use strict';
angular
.module('app.orders')
.config(['$stateProvider', config]);
//config.$inject = ['$stateProvider'];
function config($stateProvider) {
$stateProvider
.state('orders',{
// params: {customerid: null},
url:'/customers:customerId',
//templateUrl: './components/orders/orders.html',
templateUrl: 'components/orders/orders.html',
controller: 'OrdersController',
controllerAs: 'ctrl'
// resolve: {
// customerId:[ '$stateParams','customerFactory', function( $stateParams, customerFactory) {
// return customerFactory.getCustomers($stateParams.id);
// }]
// }
})
};
// 'use strict';
angular
.module('app.orders')
.controller('OrdersController', OrdersController);
OrdersController.$inject = ['$stateParams'];
function OrdersController($stateParams) {
console.log('in');
var vm = this;
vm.title = "Customer Orders " + $stateParams.customerId;
vm.customer = null;
}
And this is the working template components/orders/orders.html:
<div >
<h3>current state name: <var>{{$state.current.name}}</var></h3>
<h5>title</h5>
<pre>{{ctrl.title}}</pre>
...
When I call it like this:
<li ng-repeat="cust in [{id:1}, {id:2}]"
><a ui-sref="orders({customerId: cust.id})">View Orders - cust ID == {{cust.id}}</a>
</li>
Check it in action here
So, whil my previous answer was about make the state working without resolve, now we will observe few adjustments (and one fix) to make even resolve working.
There is a working plunker, extending the previous one.
FIX
The only fix, the most important change come from this definition:
angular
.module('app.services',[])
.factory('customersFactory', customersFactory);
see the plural in the factory name, the 'customersFactory'. While here:
...my main problem is the resolve. This is blocking me from getting into the next controller....
resolve: {
customerId:[ '$stateParams','customerFactory', function( $stateParams, customerFactory) {
return customerFactory.getCustomers($stateParams.id);
}]
}
we ask for 'customerFactory' (singular, no s in the middle)
Few improvements:
So, this would be our adjusted state def:
$stateProvider
.state('orders',{
// INTEGER is here used to later easily use LO_DASH
url:'/customers{customerId:int}', // int is the type
templateUrl: './components/orders/orders.html',
controller: 'OrdersController',
controllerAs: 'ctrl',
resolve: {
// wrong name with 's'
//customerId:[ '$stateParams','customerFactory',
// we use customer, because we also changed the factory
// implementation - to return customer related to
// $statePrams.customerId
customer:[ '$stateParams','customersFactory',
function( $stateParams, customersFactory) {
return customersFactory
//.getCustomers($stateParams.id)
.getCustomer($stateParams.customerId)
;
}]
}
})
Now, this is our adjusted factory, and its new method getCustomer
angular
.module('app.services', [])
.factory('customersFactory', customersFactory);
customersFactory.$inject = ['$http', '$log', '$q', '$stateParams'];
function customersFactory($http, $log, $q, $stateParams) {
return {
getCustomers: getCustomers,
getCustomer: getCustomer
};
function getCustomers() {
// see plunker for this, or above in question
}
// new function
function getCustomer(id) {
var url = "customer.data.json";
return $http
.get(url, {
catch: true
})
.then(function(response){
var data = response.data;
var customer = _.find(data, {"id" : id});
return customer;
})
;
}
}
this is our data.json:
[
{
"id" : 1, "name": "Abc", "Code" : "N1"
},
{
"id" : 2, "name": "Def", "Code" : "N22"
},
{
"id" : 3, "name": "Yyz", "Code" : "N333"
}
]
And here we have controller:
OrdersController.$inject = ['$stateParams', 'customer'];
function OrdersController($stateParams, customer) {
console.log('in');
var vm = this;
vm.title = "Customer Orders " + $stateParams.customerId;
vm.customer = customer;
}
a view to show customer
<h3>customer</h3>
<pre>{{ctrl.customer | json}}</pre>
Check it here in action

AngularJS controller testing scope undefined

I'm having an issue testing an AngularJS controller. The controller uses a
service to fetch some data and put it on the $scope.
// src/controllers/posts.js
module.exports = ['$scope', 'posts', function($scope, posts) {
posts.refresh(function(err, data) {
$scope.posts = data;
});
}]
// src/services/posts.js
module.exports = ['$http', function($http) {
this.refresh = function(callback) {
$http.get('/posts')
.success(function(data, status, headers, config) {
callback(null, data);
})
.error(function(data, status, headers, config) {
});
};
}]
// src/app.js
var angular = require('angular');
var PostsController = require('./controllers/posts');
var PostsService = require('./services/posts');
var simpleApp = angular.module('simple-app', []);
simpleApp.controller('PostsController', PostsController);
simpleApp.service('posts', PostsService);
This all works when I run it in the browser. I have a functioning test for the service that works with Karma and Jasmine. The problem I'm having with the controller test is that the result is that $scope is undefined.
Here is the test:
// test/controllers/posts.test.js
var fixtures = require('../fixtures/posts');
describe('PostsController', function() {
var PostsController, scope;
beforeEach(angular.mock.module('simple-app'));
beforeEach(angular.mock.inject(function($rootScope, $controller, _posts_) {
scope = $rootScope.$new();
PostsController = function() {
return $controller('PostsController', {
$scope: scope,
posts: _posts_
});
};
}));
it('should set the posts on the scope', function() {
debugger; // shows me that the scope's posts property isn't set
var controller = PostsController();
expect(scope.posts).toEqual(fixtures);
});
});
From the documentation, $controller returns a new instance of the specified controller. So when I'm calling PostsController() it should return the new instance with the dependencies injected right? When the instance is instantiated it should run the controller function, manipulating the scope that was injected in the test. Is there something I'm missing?
EDIT: I've added $httpBackend to the test but now the test says httpBackend is undefined. Here's the code (only the functions that changed):
beforeEach(angular.mock.inject(
function($rootScope, $controller, _posts_, $httpBackend) {
scope = $rootScope.$new();
PostsController = function() {
return $controller('PostsController', {
$scope: scope,
posts: _posts_
});
httpBackend = $httpBackend;
};
}));
it('should set the posts on the scope', function() {
debugger; // checking httpBackend here says httpBackend is undefined
httpBackend.whenGET('/posts').respond(fixtures);
var controller = PostsController();
expect(scope.posts).toEqual(fixtures);
});

Router resolve will not inject into controller

I have tried everything to get ui-router's resolve to pass it's value to the given controller–AppCtrl. I am using dependency injection with $inject, and that seems to cause the issues. What am I missing?
Routing
$stateProvider.state('app.index', {
url: '/me',
templateUrl: '/includes/app/me.jade',
controller: 'AppCtrl',
controllerAs: 'vm',
resolve: {
auser: ['User', function(User) {
return User.getUser().then(function(user) {
return user;
});
}],
}
});
Controller
appControllers.controller('AppCtrl', AppCtrl);
AppCtrl.$inject = ['$scope', '$rootScope'];
function AppCtrl($scope, $rootScope, auser) {
var vm = this;
console.log(auser); // undefined
...
}
Edit
Here's a plunk http://plnkr.co/edit/PoCiEnh64hR4XM24aH33?p=preview
When you use route resolve argument as dependency injection in the controller bound to the route, you cannot use that controller with ng-controller directive because the service provider with the name aname does not exist. It is a dynamic dependency that is injected by the router when it instantiates the controller to be bound in its respective partial view.
Also remember to return $timeout in your example, because it returns a promise otherwise your argument will get resolved with no value, same is the case if you are using $http or another service that returns a promise.
i.e
resolve: {
auser: ['$timeout', function($timeout) {
return $timeout(function() {
return {name:'me'}
}, 1000);
}],
In the controller inject the resolve dependency.
appControllers.controller('AppCtrl', AppCtrl);
AppCtrl.$inject = ['$scope', '$rootScope','auser']; //Inject auser here
function AppCtrl($scope, $rootScope, auser) {
var vm = this;
vm.user = auser;
}
in the view instead of ng-controller, use ui-view directive:
<div ui-view></div>
Demo
Here is how I work with resolve. It should receive promise. So I create service accordingly.
app.factory('User', function($http){
var user = {};
return {
resolve: function() {
return $http.get('api/user/1').success(function(data){
user = data;
});
},
get: function() {
return user;
}
}
});
This is main idea. You can also do something like this with $q
app.factory('User', function($q, $http){
var user = {};
var defer = $q.defer();
$http.get('api/user/1').success(function(data){
user = data;
defer.resolve();
}).error(function(){
defer.reject();
});
return {
resolve: function() {
return defer.promise;
},
get: function() {
return user;
}
}
});
These are almost identical in action. The difference is that in first case, service will start fetching date when you call resolve() method of service and in second example it will start fetch when factory object is created.
Now in your state.
$stateProvider.state('app.index', {
url: '/me',
templateUrl: '/includes/app/me.jade',
controller: function ($scope, $rootScope, User) {
$scope.user = User.get();
console.log($scope.user);
},
controllerAs: 'vm',
resolve: {
auser: function(User) {
return User.resolve()
}
}
});

How to pass data to different controller in my case?

I am trying to create factory for the restful services.
I need to make service calls. First call's data will be used to get the second calls data.
My problem is I don't know how to transfer data from one controller to another controller.
Is there a better way to do my codes?
Here are my codes...
var app = angular.module('myApp', []);
//getting init data via service
app.factory('myService', function($http) {
var myService = {
async: function() {
var promise = $http.get('test/test.json').then(function (response) {
return response.data;
});
return promise;
}
};
return myService;
});
//retrieve data
app.controller('testCtrl', function(myService, $scope, $http) {
myService.async().then(function(data) {
$scope.data = data
//using retrieve data to get another piece of data
vay first = data[0].employee[0];
})
$http({
url: "test?" + first +'.json',
method: "GET",
}).success(function(secondData) {
$scope.secondData=secondData //How do I pass data to my secondCtrl?
})
})
app.controller('secondCtrl', function($scope) {
// I need to be able to get the secondData from testCtrl.
console.log($scope.secondData)
})
Thanks for the help!
Why don't you store the data as an object in the service itself, then both controllers depend on the service and have access to the data. Like this:
app.factory('myService', function($http) {
var that = this;
var myService = function($http) {
this.set = function(url) {
var promise = $http.get(url).then(function (response) {
that.data = promise.data;
});
return promise;
}
};
return new myService($http);
});
Then your controller sets and gets the data in the way
app.controller('testCtrl', function(myService, $scope, $http) {
myService.set('someurl').then(function() {
$scope.data = myservice.data;
//using retrieve data to get another piece of data
vay first = data[0].employee[0];
myservice.set('someOtherUrl?data='+first);
})
app.controller('secondCtrl', function($scope, myservice) {
//the data object on the myservice function has been changed on the first controller and we can reasonably expect the data we need. If these 2 controllers coexist in the same space and time we can wrap this in a $watch service
console.log(myservice.data)
});
$watch service example
app.controller('secondCtrl', function($scope, $watch, myservice) {
$watch('myservice.data', function(newval, oldval) {
console.log(newval);
}, true)
//I will only log the newvalue of myservice.data when the data has changed. the last true argument is a neccesity so that angular will compare the values within the object
});
You could either extend 'myService' to contain the response data, using it in both controllers, or you could create another service for sharing data between them.
Both solutions would look similar, but here is what the second option (new service) might look like:
Factory
.factory('SharedService', function(){
var shared = {
data: ''
}
return shared;
})
This factory could act as just a place to store some data. In fact, if all you'd like to do is share data, you could just use a value provider. But a factory you could later extend with a more complex data structure and methods.
In your controllers, just inject the service and, optionally, set it to a scope variable:
Controller 1
.controller('FirstController', function($scope, SharedService){
$scope.shared = SharedService;
$scope.shared.data = 'foo';
})
$scope.shared now references the service object. If you were to do the same in the other controller, they could both read/write to that same object:
Controller 2
.controller('SecondController', function($scope, SharedService){
$scope.shared = SharedService;
console.log($scope.shared.data); // 'foo' if called after first ctrl set it
})
Demo

Categories