The ui router resolve result data is not injected in the controller - angularjs

In my SchoolyearController the parameter schoolyears is undefined.
How can I retrieve my schoolyears objects in the schoolyearService and inject the result into the SchoolyearController?
SERVICE
'use strict';
angular.module('schoolyear').service('schoolyearService', function ($http) {
return {
getSchoolyears: function () {
var path = 'scripts/model/schoolyears.json';
$http.get(path).then(function (response) {
return response.data.schoolyears; // The schoolyears here are the 6 expected JS objects in an array, so far so good but how do I get those objects into the SchoolyearController as parameter ?
});
}
};
});
UI-ROUTER
resolve: {
schoolyearService: ['schoolyearService',
function (schoolyearService) {
return schoolyearService.getSchoolyears();
}]
},
CONTROLLER
'use strict';
angular.module('schoolyear').controller('SchoolyearController', function ($scope, schoolyears) {
$scope.schoolyears = schoolyears; // I do not want to do a $http request here I just want to get passed the data here !!!
});
UPDATE
Still the schoolyears in the resolved property are undefined, why?
FACTORY
'use strict';
angular.module('schoolyearModule').factory('schoolyearFactory', function ($http) {
return {
getSchoolyears: function () {
var path = 'scripts/model/schoolyears.json';
$http.get(path).then(function (response) {
return response.data.schoolyears; // The schoolyears here are the 6 expected JS objects in an array
});
}
};
});
UI-ROUTER
resolve: {
schoolyears: function(schoolyearFactory) {
var schoolyears = schoolyearFactory.getSchoolyears();
return schoolyears;
}
},
CONTROLLER
'use strict';
angular.module('schoolyearModule').controller('ProjectsController', function ($scope, schoolyears) {
$scope.schoolyears = schoolyears; // I do not want to do a $http request here I just want to get passed the data here !!!
});

Your resolved value is named schoolyearService (and thus clashes with the service which has the same name):
resolve: {
schoolyearService: ...
But you're trying to inject it using the name schoolyears:
angular.module('schoolyear').controller('SchoolyearController',
function ($scope, schoolyears) {
Use the same name (schoolyears) everywhere:
resolve: {
schoolyears: ...
Also, you should use the factory() method to define your service, and not the servoce() method. The service() method takes a constructor function as argument, not a function returning an object being the actual service instance.
EDIT:
Moreover, you're not returning anything from the getSchoolyears() service method. So undefined is returned. What you need is:
getSchoolyears: function () {
var path = 'scripts/model/schoolyears.json';
return $http.get(path).then(function (response) {
return response.data.schoolyears;
});
}

Related

Provider 'myService' must return a value from $get factory method

app.factory('myService', function ($http) {
var myService;
var getData = function(link) { //function to get some data from a get request to 'link'
$http.get(link)
.success(function(response) {
myService = response.data;
});
return myService;
};
return myService;
});
I am using two controllers,one to send a request to myService to get search results from a search and storing the results in myService and the other controller is of a different page (but same app) where I have to show the results.
The controller below is to get search results and store them in myService:
app.controller('headerController', ['$scope', function($scope,$http,myService) {
$scope.search_it=function(name,link) { //this is called from html, providing the name and link arguments, with link containing the link to get data from
$scope.respons = myService.getData(link);
};
}]);
The controller below is to get data from myService to view on another page:
app.controller("resultController", function ($scope,myService) {
$scope.resJSON = myService;
});
Where is my problem? And if the code is incorrect then mention where.
You can return a promise from your factory:
app.factory('myService', function($http) {
var myService = {
getData: getData
};
return myService;
function getData(link) {
return $http.get(link);
}
});
Then, in your controller:
app.controller('headerController', function($scope, $http, myService) {
$scope.search_it = function(name, link) { //this is called from html, providing the name and link arguments, with link containing the link to get data from
function getSuccess(response) {
$scope.respons = response.data;
}
function getError(response) {
console.log(response);
}
myService.getData(link)
.then(getSuccess)
.catch(getError);
});

AngularJS: How to access variable from inside a promise and use within the controller?

I'm trying to declare an array inside a function of a controller that happens after the factory pulls for data, and then access it after the function is done being completed. Here's what I have for my code:
app.controller('SignUpController', function ($scope, $http, $location, DailyCounterService, $localStorage) {
DailyCounterService.GetDailyCountersList().then(function (d) {
$scope.DailyCounters = d.data;
$scope.allCounters = [];
var daySixteen = d.data.filter(function (d) {
// This is where I'm building the array I want to access later
$scope.allCounters.push(d.MICounter);
return d.MIDay === "16";
});
console.log($scope.allCounters);
// This prints in console '[2, 6, 1, 1, 7, 8, 2......]'
// So the array is now initialized
}, function (error) {
alert('Error!');
});
// Here is where I want to access $scope.allCounters once again
// But Can't because doing this:
console.log($scope.allCounters);
// prints 'undefined'
// How would I make $scope.allCounters be able to be accessed here?
})
.factory('DailyCounterService', function ($http) {
var fac = {};
fac.GetDailyCountersList = function () {
return $http.get('/Data/GetDailyCountersList')
}
return fac;
})
As I've asked in the comments towards the end of my controller, how would I be able to access the variable set in the function prior outside of that function?
Well, if this controller is associated with a route, then you can tie up this get code in the resolve attribute of the route provider like this,
.when("/signup", {
templateUrl: "signup.html",
controller: "SignUpController",
resolve: {
allCounters:
function(DailyCounterService){
DailyCounterService.GetDailyCountersList().then(function (d) {
// Do your stuff
return allCounters;
}, function (error) {
alert('Error!');
});
}
}
}),
and access allCounters in you controller like this,
app.controller('SignUpController', function ($scope, $http, $location, allCounters, DailyCounterService, $localStorage)
By this way all counters will always be initialized when your controller is loaded.
More on resolve: http://odetocode.com/blogs/scott/archive/2014/05/20/using-resolve-in-angularjs-routes.aspx

Cant read property from service in angular

In this case console logged all properties
app.controller("sgCtrl", function ($scope, $service)
{
var asd=service.getPerson();
console.log(asd);
}
But when im try to get some property its returned me undefined
...console.log(asd.person.Id)
My service
function service($http, $q) {
var service = {
person:[]
};
service.getPerson = function (personId) {
return $http.get('/P/GetP',
{params:{personId:personId}}).success(function (res) {
service.person = res.Person;
});
};
Issue is
1. $http.().success(function() {}) is asynchronous function. So service.person will be available only when control will come inside success callback handler.
2. You have not created service in the correct way.
You can try with below code:
Service code
function service($http, $q) {
this.getPerson = function (personId, successHandler) {
$http.get('/P/GetP',
{params:{personId:personId}}).success(function (res) {
successHandler(res.Person);
});
};
app.service('MyService', service);
Controller Code
app.controller("sgCtrl", function ($scope, MyService) {
function successHandler(person) {
console.log(person.IsActive);
}
MyService.getPerson('somePersonId', successHandler);
}
I believe it will resolve your issues.
Cheers!

Nested Chaning promise response getting undefined in Controller by using UI Route resolve

for past 3 days , i have struggling in getting a value from nested service through controller,
I have a service 1 call and pass the service 1 call to service 2 and getting a response and pass to controller,In controller , i am getting undefined.
So when i pass a single response call , that means service1 call , getting a value in controller by using Ui route resolve.
What wrong here ?
This is my factory call.
app.factory('LogHomService', function (Service1, Service2)
{
var MyService = function (data)
{
Service1.log("user", encodeURIComponent("ad"))
.then(function(response) {
var FullUrl = response.strURL;
var objs = response.products; // getting the response here
Service2.pageLoad(objs)
.then(function(response) {
var homeScreen = response; // getting the response here
return homeScreen;
});
});
};
return {
MyService: MyService
}
});
Route call:
.state('home.prod', {
url: '/product',
views: {
'#': {
templateUrl: baseUrl + 'home/product',
controller: 'productController'
}
},
resolve: {
param2: function(LogHomService) {
return LogHomService.MyService();
}
}
})
Controller:
var productController = function ($scope, $rootScope, $state, $stateParams,param2)
{
console.log(param2); // getting undefined
}
productController.$inject = ['$scope', '$rootScope', '$state','$stateParams','param2');
Note:
When I return a single response getting a value in controller which means return a service 1 call getting response.
When i tried to return a service2 call getting undefined.
This is my factory call.
app.factory('LogHomService', function (Service1, Service2)
{
var MyService = function (data)
{
Service1.log("user", encodeURIComponent("ad"))
.then(function(response) {
var FullUrl = response.strURL;
var objs = response.products; // getting the response here
return objs;
});
};
return {
MyService: MyService
}
});
In response to your question in the comments, in order to access the data in the service in your controller, you could do something like this:
app.factory('LogHomService', function (Service1, Service2) {
var service = {}
service.myMethod = function (data) {
Service1.log("user", encodeURIComponent("ad"))
.then(function(response) {
var FullUrl = response.strURL;
//at this point, you will have access to LogHomService.objs
service.objs = response.products;
return service.objs;
});
};
return service
});
This line:
return LogHomService.MyService();
will always return null because MyService function returns nothing.
Here is a purposed fix:
var MyService = function (){
return Service1.log("user", encodeURIComponent("ad"))
.then(function(response) {
var FullUrl = response.strURL;
var objs = response.products;
return Service2.pageLoad(objs);
};
}
I've also cleared some unnecessary stuff.
Service2 object response from the controller,In controller getting Function call when i use return LogHomService.MyService; if i use return LogHomService.MyService(); shows undefined. i will attached the screenshot below.
But in Service response have values , Don't know why.
When I click the data , its shows factory code.

Getting Undefined in controller

I'm trying to get the value from service and then printing that value in console log which is giving me undefined in controller.
The value from service is being returned properly. But I'm not able to access vm.rrsData outside getRRSDetails function. vm.rrsData is comming as undefined outside the function.
Please suggest.
my controller :
(function () {
'use strict';
var angular = window.angular;
function RRSCtrl(
$translate,
RRSSvc
) {
var vm = this;
// Private
function getRRSDetails() {
RRSSvc.getRRSDetails()
.then(function (data) {
vm.rrsData = data;
});
}
getRRSDetails();
console.log('vm.rrsData'+ JSON.stringify(vm.rrsData)); // returning undefined here
}
angular
.module('quote')
.controller('RRSCtrl', [
'$translate',
'RRSSvc',
RRSCtrl
]);
}());
my service :
(function () {
'use strict';
var angular = window.angular;
function RRSSvc(
$http,
$q,
UserSvc,
UtilitiesSvc
) {
function rrsError(messageKey) {
UtilitiesSvc.showMessage(messageKey, 'error', 'generate-blank-demo-error');
}
function getRRSDetails(poID) {
return $http.get('quote/accounts/' + UserSvc.get('accountId') + '/pos/' + poID + '/rrs?serialNumber=')
.then(function (response) {
return response.data;
})
.catch(function (e) {
rrsError('quote.messages.GET_RRS_ERROR');
$q.reject(e);
});
}
return {
getRRSDetails: getRRSDetails
};
}
angular.module('quote')
.service('RRSSvc', [
'$http',
'$q',
'UserSvc',
'UtilitiesSvc',
RRSSvc
]);
}());
That's completely normal since you're making an asynchronous request.
consider these 2 lines:
getRRSDetails();
console.log('vm.rrsData'+ JSON.stringify(vm.rrsData)); // returning undefined here
console.log will run before the function above resolves. So, at that time vm.rrsData is undefined.
To see the value you must include console.log inside the function:
function getRRSDetails() {
RRSSvc.getRRSDetails()
.then(function (data) {
vm.rrsData = data;
console.log('vm.rrsData'+ JSON.stringify(vm.rrsData)); // has value from the http call
});
}
UPDATE
Another way to write the above and maybe more clear:
RRSSvc.getRRSDetails().then(onRSSDetails);
function onRSSDetails(response) {
// here you do whatever you want with data.
console.log(response);
}
Try to call your service in controller like this:
this.rrsData = null; //declare variavle to store service data
RRSSvc.getRRSDetails()
.then(function (data) {
this.rrsData = data;
}.bind(this)); // bind is the key to store the context
console.log('rrsData'+ JSON.stringify(this.rrsData));

Resources