AngularJS: How to fetch data of specific id from JSON file - javascript

In my controller class I fetch the id of specific user from URL and then send it to service OrderService Now in the service I want to retrieve the data of this id from JSON file , How can I achieve this ?
OrderCtrl
'use strict';
angular.module('Orders').controller('OrderCtrl', ['$scope', '$state', "SettingService", "OrderService","$stateParams", function($scope, $state, SettingService, OrderService,$stateParams) {
var OrderId = $stateParams.orderId;
$scope.orders = [];
OrderService.getOrderDetails(OrderId).then(function(response){
$scope.orders = response.data.data;
}, function(error){
})
}]);
OrderService.js
angular.module('Orders')
.service('OrderService', ['$http', '$state', '$resource', '$q', 'SettingService', '$localStorage', "MessageService",
function($http, $state, $resource, $q, SettingService, $localStorage, MessageService) {
var service = {
getOrderDetails : function(OrderId){
Here I want to retrieve data from JSON file
});
}
}
return service;
}]);

Try to use something like this
'use strict';
angular.module('Orders').controller('OrderCtrl', ['$scope', '$state', "SettingService", "OrderService", "$stateParams", function ($scope, $state, SettingService, OrderService, $stateParams) {
var OrderId = $stateParams.orderId;
$scope.orders = [];
OrderService.getOrderDetails(OrderId).then(function (response) {
$scope.orders = response.data.data;
});
}]);
// I act a repository for the remote json collection.
angular.module('Orders').service("OrderService", ['$http', '$state', '$resource', '$q', 'SettingService', '$localStorage', "MessageService",
function ($http, $state, $resource, $q, SettingService, $localStorage, MessageService, handleResponse) {
// Return public API.
return ({
getOrderDetails: getOrderDetails
});
// I get all the remote collection.
function getOrderDetails(OrderId) {
var request = $http({
method: "get",
url: '/ajax/order/details', // for example
params: {'id': OrderId}
});
return (request.then(handleResponse.success, handleResponse.error));
}
}]);
angular.module('Orders').service('handleResponse', function ($http, $q, $location) {
return {
error: function (response) {
// The API response from the server should be returned in a
// nomralized format. However, if the request was not handled by the
// server (or what not handles properly - ex. server error), then we
// may have to normalize it on our end, as best we can.
if (!angular.isObject(response.data) || !response.data.message) {
// Something was wrong, will try to reload
return ($q.reject("An unknown error occurred."));
}
// Otherwise, use expected error message.
return ($q.reject(response.data.message));
},
success: function (response) {
return (response.data);
}
};
});

Related

Cannot read propery getRiders of undefined

I want to call a service which I defined in DeliverService but when I called it from controller it gives an error of Cannot read propery getRiders of undefined , NO idea why this happened :|
DeliverService.js
angular.module('Deliver')
.service('DeliverService', ['$http', '$state', '$resource', '$q', 'SettingService', '$localStorage', "MessageService", function($http, $state, $resource, $q, SettingService, $localStorage, MessageService) {
var service = {
getRiders : function(){
return $http.get("Hero.json");
//return $http.get(SettingService.baseUrl + "api/orders");
} }
return service;
}]);
DeliverCtrl.js
use strict';
angular.module('Deliver').controller('DeliverCtrl',['$scope','$state', "SettingService","DeliverService", function($scope, $state, $ionicModal, MessageService, SettingService,DeliverService) {
$scope.riders = [];
DeliverService.getRiders().then(function(response){
$scope.riders = response.data.data;
}, function(error){
});
}]);
Your dependencies aren't in the matching order here. Hence, DeliverService isn't actually injected.
Your controller code should look something like this:
angular.module('Deliver').controller('DeliverCtrl',
['$scope','$state', '$ionicModal', 'MessageService', 'SettingService','DeliverService',
function($scope, $state, $ionicModal, MessageService, SettingService, DeliverService) {
$scope.riders = [];
DeliverService.getRiders().then(function(response){
$scope.riders = response.data.data;
}, function(error){});
}]);
In DeliverCtrl.js
The injection Parameter and function parameters do not match
It should be like this
['$scope','$state','$ionicModal','MessageService','SettingService','DeliverService', function($scope, $state, $ionicModal, MessageService, SettingService,DeliverService)

Service undefined when injected into controller

I have a controller that I have injected a factory into but it comes back as undefined when I call a method on that factory. Not sure what I am doing wrong here. Any help would be appreciated.
Factory:
(function(){
'use strict';
// Declare factory and add it 'HomeAutomation' namespace.
angular.module('HomeAutomation').factory('AuthenticationService', ['$http','$localStorage', '$window', function($http, $localStorage, $window){
var service = {};
service.login = Login;
service.logout = Logout;
service.parseJWT = parseJWT;
service.loginStatus = loginStatus;
return service;
function Login(email, password, callback){
$http.post('api/user/login', {email: email, password: password})
.success(function(res){
// Login successful if there is a token in the response.
if(res.token){
// store username and token in local storage to keep user logged in between page refreshes
$localStorage.currentUser = { email: email, token: res.token };
// add jwt token to auth header for all requests made by the $http service
$http.defaults.headers.common.Authorization = 'Bearer ' + res.token;
callback(true);
}else{
callback(res);
}
}).error(function(err){
console.log(err);
});
}
function Logout(){
$localStorage.currrntUser
}
function parseJWT(token){
var base64URL, base64;
base64URL = token.split('.')[1];
base64 = base64URL.replace('-', '+').replace('_', '/');
console.log(JSON.parse($window.atob(base64)));
}
function loginStatus(){
if($localStorage.currentUser){
return true;
}else{
return false;
}
}
}]);}());
Controller:
(function(){
angular.module('HomeAutomation')
.controller('loginController', ['$scope', '$location', 'AuthenticationService', function($scope, $location, $localStorage, AuthenticationService){
$scope.isLoggedIn = AuthenticationService.logout();
$scope.logUserIn = function(){
AuthenticationService.login($scope.login.email, $scope.login.password, function(result){
if(result === true){
$location.path('/');
}else{
console.log(result);
}
});
};
$scope.logUserOut = function(){
AuthenticationService.logOut();
}
}]);}());
This is the line that is causing the err:
$scope.isLoggedIn = AuthenticationService.logout();
Apparently "AuthenticationService" is undefined. Not sure why.
Thanks in advance.
You messed up with depedency sequence, you need to remove $localStorage from controller factory function since $localStorage isn't use anywhere in controller & haven't injected in DI array.
.controller('loginController', ['$scope', '$location', 'AuthenticationService',
function($scope, $location, AuthenticationService){
//^^^^^^^^^^removed $localStorage dependency from here
NOTE: Always make sure when you inject any dependency in DI array, they should used in same sequence in controller function
The injection is not good :
.controller('loginController', ['$scope', '$location', 'AuthenticationService', function($scope, $location, $localStorage, AuthenticationService){
Try with this :
.controller('loginController', ['$scope', '$location', '$localStorage', 'AuthenticationService', function($scope, $location, $localStorage, AuthenticationService){
I don't know which builder you use, but for example with Gulp, you can use gulp-ng-annotate that will do the job for you so that you can only write :
.controller('loginController', function($scope, $location, $localStorage, AuthenticationService){
without the array. The ng-annotate will take care of the rest.

Issue with Url redirect on $location in Angularjs - Cannot read property 'path' of undefined

I'm new to AngularJS and I'm trying to run this AngularJS that should modify the URL without reloading the page when I click on my submit button but in console I get TypeError: Cannot read property 'path' of undefined.
Can't really see where I missed $location injection.
What could be the problem?
var app = angular.module("SearchAPP", ['ngRoute']);
app.run(['$route', '$rootScope', '$location',
function($route, $rootScope, $location) {
var original = $location.path;
$location.path = function(path, reload) {
if (reload === false) {
var lastRoute = $route.current;
var un = $rootScope.$on('$locationChangeSuccess', function() {
$route.current = lastRoute;
un();
});
}
return original.apply($location, [path]);
};
}
]);
app.controller('GetController', ['$http', '$scope', '$location',
function($http, $scope, $rootScope, $location) {
$scope.click = function() {
var response = $http({
url: 'http://localhost:4567/search',
method: "GET",
params: {
keyword: $scope.searchKeyword
}
});
response.success(function(data, status, headers, config) {
$scope.searchResults1 = data;
// $http.defaults.useXDomain = true;
$location.path('/' + $scope.searchKeyword, false);
});
response.error(function(data, status, headers, config) {
alert("Error.");
});
};
}
]);
Wrong dependency sequence in DI array, $rootScope is missing from DI array 3rd parameter. Make sure injected dependency should be using in same sequence in controller function
// VVVVVVVV $rootscope was missing
app.controller('GetController', ['$http', '$scope', '$rootScope','$location',
function($http, $scope, $rootScope, $location) {

Angular watch factory value

Say i have the following factory:
app.factory("categoryFactory", function (api, $http, $q) {
var selected = null;
var categoryList = [];
return {
getList: function () {
var d = $q.defer();
if(categoryList.length <= 0){
$http.get(api.getUrl('categoryStructure', null))
.success(function (response) {
categoryList = response;
d.resolve(categoryList);
});
}
else
{
d.resolve(categoryList)
}
return d.promise;
},
setSelected: function (category) {
selected = category;
},
getSelected: function () {
return selected;
}
}
});
now i have two controllers using this factory at the same time. Because of this both controllers has to be notified when updated for this i attempted the following:
app.controller('DashboardController', ['$http', '$scope', '$sessionStorage', '$log', 'Session', 'api','categoryFactory', function ($http, $scope, $sessionStorage, $log, Session, api, categoryFactory) {
$scope.selectedCategory = categoryFactory.getSelected();
}]);
While my other controller looks like this:
app.controller('NavController', ['$http', '$scope', '$sessionStorage', '$log', 'Session', 'api', 'FileUploader', 'categoryFactory', function ($http, $scope, $sessionStorage, $log, Session, api, FileUploader, categoryFactory) {
$scope.categories = [];
categoryFactory.getList().then(function (response) {
$scope.categories = response;
});
$scope.selectCategory = function (category) {
categoryFactory.setSelected(category);
}
}]);
how ever when the NavController changed the value it was not changed in the DashboardController
My question is how can i either watch or in another way get notified when the value changes?
You can use an observer pattern, like so:
app.factory("categoryFactory", function (api, $http, $q) {
// the list of callbacks to call when something changes
var observerCallbacks = [];
// ...
function notifyObservers() {
angular.forEach(observerCallbacks, function(callback) {
callback();
});
}
return {
setSelected: function (category) {
selected = category;
// notify the observers after you change the value
notifyObservers();
},
registerObserver: function(callback) {
observerCallbacks.push(callback);
}
}
});
And then in your controllers:
app.controller('NavController', ['$http', '$scope', '$sessionStorage', '$log', 'Session', 'api', 'FileUploader', 'categoryFactory', function ($http, $scope, $sessionStorage, $log, Session, api, FileUploader, categoryFactory) {
// ...
// init
(function() {
categoryFactory.registerObserver(function() {
categoryFactory.getList().then(function (response) {
$scope.categories = response;
});
});
})();
}]);
This way, any time setSelected is called, it calls each callback that you've registered in observerCallbacks. You can register these from any controller since factories are singletons and they will always be in the know.
Edit: just want to add that I may have put the notifyObservers() call in the wrong area (currently in setSelected) and that I may be putting the wrong update call in the controller (currently getList) but the architecture remains the same. In the registerObserver, put whatever you want to do when the values are updated and wherever you make changes that you want observers to know about call notifyObservers()
You could follow dot rule here so that prototypal inheritance will get followed.
Basically you need to have one object inside your service that will have selected variable, And will get rid of getSelected method.
Factory
app.factory("categoryFactory", function(api, $http, $q) {
var categoryFactory = {};
categoryFactory.getList = function() {
var d = $q.defer();
if (categoryList.length <= 0) {
$http.get(api.getUrl('categoryStructure', null))
.success(function(response) {
categoryList = response;
d.resolve(categoryList);
});
} else {
d.resolve(categoryList)
}
return d.promise;
}
categoryFactory.setSelected = function(category) {
categoryFactory.data.selected = category;
}
categoryFactory.data = {
selected: null
}
return categoryFactory;
});
Controller
app.controller('DashboardController', ['$http', '$scope', '$sessionStorage', '$log', 'Session', 'api', 'categoryFactory',
function($http, $scope, $sessionStorage, $log, Session, api, categoryFactory) {
//this will provide you binding without watcher
$scope.selection = categoryFactory.data;
}
]);
And then use {{selection.selected}} on html part will update a value when changes will occur in selection.

AngularJS $scope.foo is set with service, but later on in the same controller undefined

I have a service which calls API and gets json response. I inject this service into my controller and try to set $scope.tank variable with this received data. When I try to use this variable later on (in the same controller!) it is undefined. But the funny thing is that data is displayed in the front-end.
I've looked all over stackoverflow and I can not figure this out. I have created a plunker example - http://plnkr.co/edit/DkFNE8E9897dSF19eaU9?p=preview
My service:
appServices.service('TankService', function($q, $http) {
var data, deferred = $q.defer();
return {
init: function(id) {
var defer = $q.defer();
$http.get(options.api.base_url, { cache: 'true'})
.success(function(response) {
data = response;
deferred.resolve(data);
});
},
// return promise
getData: function() {
return deferred.promise;
}
};
});
I call my data in controller like this:
appControllers.controller('TankViewCtrl', ['$rootScope', '$scope', '$q', '$routeParams', '$location', '$sce', '$route', 'TankService',
function TankViewCtrl($rootScope, $scope, $q, $routeParams, $location, $sce, $route, TankService) {
var id = $routeParams.tank_id;
$scope.id = id;
$scope.tank = [];
// call our data
TankService.init(id);
TankService.getData().then(function(data){
$scope.tank = data;
});
// why is this undefined?
console.log($scope.tank);
}
]);
Thank in advance for your help!
HTTP calls are asynchronous requests.
You're asking your controller to display the result of the request without making sure you had an answer beforehand. That's why you get undefined.
Use :
TankService.getData().then(function(data){
$scope.tank = data;
console.log($scope.tank);
});

Categories