Angularjs - Restangular call inside factory/service - angularjs

I am using factory as follows:
var appModule = angular.module('appModule', ['ngRoute','restangular']);
appModule
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/home', {
templateUrl: 'home.html',
controller: 'ngHomeControl'
})
.when('/contacts', {
templateUrl: 'contacts.html',
controller: 'ngContactControl'
});
}]);
appModule
.factory('testFactory', function testFactory(Restangular) {
return {
getFriendList: function() {
return Restangular
.all('api/users/getfriendsinvitations/')
.getList()
.then(function(response) {
//
});
}
}
});
appModule
.controller('ngHomeControl', function($scope, testFactory) {
$scope.homeFriends = testFactory.getFriendList();
});
appModule
.controller('ngContactControl', function($scope, testFactory) {
$scope.contactFriends = testFactory.getFriendList();
});
Here I can't get the value for $scope.homeFriends & $scope.contactFriends from the Restangular call. Can anyone suggest to me how to get values from Restangular call using factory/service?

Finally I found:
appModule
.factory('testFactory', ['Restangular', function(Restangular) {
return {
getFriendList: Restangular
.all('api/users/getfriendsinvitations/')
.getList();
}
}]);
testFactory.getFriendList.then(function(homeFriends) {
$scope.homeFriends = homeFriends;
}

Related

Angular Routing and Binding data from controller

I have my angular routing like th below code
var app = angular.module('mainApp', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider.when('/', {
templateUrl: '/DeclarationForms/V1/EmployeeProfile.html',
controller: 'empController'
}).when('/DeclarationAndIndemnityBond.html', {
templateUrl: '/DeclarationForms/V1/DeclarationAndIndemnityBond.html',
controller: 'declarationController'
}).otherwise({
redirectTo: "/"
});
app.controller('empController', function ($scope, $http) {
var resultPromise = $http.get("../ViewForms/GetData/", { params: { ProcName: "SP_EmployeeProfile_GetList" } });
resultPromise.success(function (data) {
console.log(data);
$scope.employeeProfile = data;
});
});
});
The empController calls my controller action with a parameter as per the code
$http.get("../ViewForms/GetData/", { params: { ProcName: "SP_EmployeeProfile_GetList" } });
The controller's action code is as follows
[HttpGet]
[AllowAnonymous]
public ActionResult GetData(string ProcName)
{
if(Session["UserJDRECID"]==null || Session["UserJDRECID"].ToString()=="0")
{
return RedirectToAction("Login", "User_Login");
}
else
{
var UsrJDID = Convert.ToInt32(Session["UserJDRECID"]);
DataSet dt = Helper.PopulateData(ProcName, UsrJDID);
string JSONString = string.Empty;
JSONString = JsonConvert.SerializeObject(dt);
return Json(JSONString, JsonRequestBehavior.AllowGet);
}
}
The form get loaded properly as per the code
templateUrl: '/DeclarationForms/V1/EmployeeProfile.html',
but it don't call my action GetData from where I suppose to bind the EmployeeProfile.html
If I change my angular controller like below code this still don't work
app.controller('empController', function ($scope)
{
console.log("hi"); alert();
});
My console gives below error
Error: error:areq
Bad Argument
Please help me I stuck here.
Thanks in advance.
You can't use "../" inside your $http.get.
I don`t know how your project is setup, but you can try:
$http.get("/ViewForms/GetData/", { params: { ProcName: "SP_EmployeeProfile_GetList" } });
In that case the ViewForms is the name of your controller and it needs to be in the root or pass the complete url. Make sure you are passing all the folders then Controller then your action.
Example: http://www.dotnetcurry.com/angularjs/1202/angular-http-service-aspnet-mvc
I change my code as follows and this worked for me.
var app = angular.module('mainApp', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider.
when('/', {
templateUrl: '/DeclarationForms/V1/EmployeeProfile.html',
controller: 'empController'
})
otherwise({
redirectTo: "/"
});
});
app.controller('empController', ['$scope', '$http', EmployeeProfile]);
function EmployeeProfile($scope, $http) {
$http.get("../ViewForms/GetData", { params: { ProcName: "SP_EmployeeProfile_GetList" } })//Done
.then(function (response) {
var mydata = $.parseJSON((response.data));
$scope.employeeProfile = $.parseJSON(mydata);
});
}

Angular factory $resource: 404 Not Found

I'm new to Angular and I've been working on an Airline SPA which reads sample data from json file. The app works fine when running on nodejs (localhost:3000/airports), however it shows this error when I check it out on github: GET https://nlmazhari.github.io/airports 404 Not Found
this is my app.js:
angular.module('airline', ['airlineServices'])
.config(airlineRouter);
function airlineRouter ($routeProvider) {
$routeProvider
.when('/', {templateUrl: 'partials/destinations.html',
controller: 'DestinationsCtrl'})
.when('/airports/:airportCode', {
templateUrl: 'partials/airport.html',
controller: 'AirportCtrl'
})
.when('/flights', {
templateUrl: 'partials/flights.html',
controller: 'FlightsCtrl'})
.when('/reservations', {
templateUrl: 'partials/reservations.html',
controller: 'ReservationsCtrl'});
}
these are my controllers:
function AirportCtrl ($scope, $routeParams, Airport) {
$scope.currentAirport = Airport.get({
airportCode: $routeParams.airportCode
});
}
function DestinationsCtrl ($scope, Airport) {
$scope.setActive('destinations');
$scope.sidebarURL = 'partials/airport.html';
$scope.currentAirport = null;
$scope.setAirport = function (code) {
$scope.currentAirport = Airport.get({airportCode: code});
};
$scope.airports = Airport.query();
}
and this is my services.js:
angular.module('airlineServices', ['ngResource'])
.factory('Airport', function ($resource) {
return $resource('/airports/:airportCode');
})
.factory('Flights', function ($resource) {
return $resource('/flights');
})
.factory('Reservations', function ($resource) {
return $resource('/reservations');
});
can anybody guide me? why am I getting this error?

AngularJS: Error on Factory and routeProvider

In "routeProvider" I have the "objectStats" on resolve, but my controller does not seem to understand it. (I found several problems like on stackoverflow, but no solution solved my error)
My code:
var app = angular.module('AppLearning', ['ngRoute','easypiechart']);
app.config(['$routeProvider',function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'index.html',
controller: 'AppCtrl',
resolve: {
objectStats: function(statsFactory) {
return statsFactory.getStatsFollow();
}
}
}).
otherwise({
redirectTo: '/home'
});
}]);
app.controller('AppCtrl', ['$scope', '$http', 'objectStats', function ($scope, $http, objectStats) {
$scope.statsUnfollow = objectStats.data;
$scope.percent = 65;
$scope.pieOptions = {
animate:{
duration:2000,
enabled:true
},
trackColor: '#e5e5e5',
barColor: '#3da0ea',
scaleColor:false,
lineWidth:5,
lineCap:'square'
};
}]);
app.factory('statsFactory', ['$http', function($http) {
return {
//Code edited to create a function as when you require service it returns object
//by default so you can't return function directly. That's what understand...
getStatsFollow: function (type) {
var q = $q.defer();
$http.get('/api/stats/follow').success(function (data) {
q.resolve(function() {
var settings = jQuery.parseJSON(data);
return settings[type];
});
});
return q.promise;
}
}
}]);
Error: [$injector:unpr] Unknown provider: objectStatsProvider <- objectStats
http://errors.angularjs.org/1.2.9/$injector/unpr?p0=objectStatsProvider%20%3C-%20objectStats
minErr/<#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:78:12
createInjector/providerCache.$injector<#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:3546:19
getService#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:3673:39
createInjector/instanceCache.$injector<#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:3551:28
getService#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:3673:39
invoke#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:3700:1
instantiate#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:3721:23
$ControllerProvider/this.$gethttps://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:6772:18
nodeLinkFn/<#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:6185:34
forEach#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:310:11
nodeLinkFn#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:6172:11
compositeLinkFn#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:5636:15
compositeLinkFn#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:5639:13
compositeLinkFn#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:5639:13
publicLinkFn#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:5541:30
bootstrap/doBootstrap/https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:1304:11
$RootScopeProvider/this.$gethttps://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:11955:16
$RootScopeProvider/this.$gethttps://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:12055:18
bootstrap/doBootstrap/<#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:1302:9
invoke#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:3710:14
bootstrap/doBootstrap#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:1300:1
bootstrap#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:1314:1
angularInit#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:1263:5
#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:20555:5
b.Callbacks/c#https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js:3:7852
b.Callbacks/p.fireWith#https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js:3:8658
.ready#https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js:3:3264
H#https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js:3:693

Why can't i use the $http service in a route resolve?

I want to make my views show only after the initial data is fetched and i am trying to accomplish this with a route resolve, but i can't get it to work. What am i doing wrong? Also my angular skills are a bit shabby so i aplogize in advance if my question is dumb.
Application.js :
var Application = angular.module('ReporterApplication', ['ngRoute']);
Application.config(['$routeProvider', '$interpolateProvider',
function($routeProvider, $interpolateProvider) {
$interpolateProvider.startSymbol('<%');
$interpolateProvider.endSymbol('%>');
$routeProvider
.when('/packing/scan.html', {
templateUrl: 'packing/scan.html',
controller: 'PackingScanController',
resolve: {
initData : Application.PackingScanInit()
}
})
.when('/packing/stats.html', {
templateUrl: 'packing/stats.html',
controller: 'PackingStatisticsController'
})
etc
and here is my Scan.js file :
Application.PackingScanInit = function ($q,$timeout,$http) {
var serverData = "";
$http.get('/packing/scan.action')
.success(function(data){
serverData = data;
})
.error(function(data){
serverData = data;
});
return serverData;
}
Application.controller('PackingScanController', ['initData', '$scope', '$http', function(initData, $scope, $http) {
var packer = this;
// Message log model
packer.messageLog = [{
status : "",
message : null
}];
the files are included in this order.
service are singletons means there are initialized only one but time but if you simply return from service it will be called one time but if you return a function from service it will be called again and again .See Below Sample for working.
var app = angular.module('ajay.singhApp', [])
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/view1', {
templateUrl: 'views/main.html',
controller: 'MainCtrl',
resolve: {
myVar: function (repoService) {
return repoService.getItems().then(function (response) {
return response.data;
});
}
}
})
.when('/view2', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/view1'
});
}]);
app.factory('repoService', function ($http) {
return {
getItems: function () {
return $http.get('TextFile.txt');
}
};
});
Try this:
Application.PackingScanInit = function ($q,$timeout,$http) {
return $http.get('/packing/scan.action')
.success(function(data){
return data;
})
.error(function(data){
return data;
});
}
Also you have to adjust your resolve to this:
resolve: {
initData : Application.PackingScanInit
}
Here is a specific working example:
(function() {
angular.module('app',['ngRoute']);
function TestCtrl($scope, initData) {
$scope.value = initData;
}
angular.module('app').config(function($routeProvider) {
$routeProvider.otherwise({
template: '`<p>Dude {{value}}</p>`',
controller: TestCtrl,
resolve: {
initData: function($http) {
return $http.get('test.json') //change to test-e.json to test error case
.then(function(resp) {
return resp.data.value; //success response
}, function() {
return 'Not Found'; // error response
});
}
}
});
});
})();
http://plnkr.co/edit/SPR3jLshcpafrALr4qZN?p=preview

Write unit test for resolve function in AngularJS

I have the below code. When I run my unit tests, I get that the resolve function is not code covered.
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider.
when('/', {
controller: 'HomeCtrl',
resolve: {
homePage: function (homePageLoader) {
return homePageLoader();
}
},
templateUrl: 'views/home.html'
}).
otherwise({ redirectTo: '/' });
}]);
How do I write unit tests for the resolve function?
I had a smilar situation with my app.js with routeprovider & resolve. This was solved with below:
app.js
var appModule = angular.module('myApp',['ngRoute'])
.config(['$httpProvider', '$routeProvider', '$locationProvider', '$translateProvider', function ($httpProvider, $routeProvider, $locationProvider, $translateProvider) {
$locationProvider.html5Mode(true)
$routeProvider
.when('/services/main', {templateUrl: '/services/main/html/main.html', controller: 'MainCtrl', resolve: {
myVar: function (varService) {
return varService.invokeService();
}
}})
}])
Spec file
describe("Unit Testing: config - ", function() {
var appModule;
var mockService;
beforeEach(function() {
appModule = angular.mock.module("myApp");
});
it('should test routeProvider resolve', function() {
mockService = {
invokeService: jasmine.createSpy('invokeService').andReturn('myVar')
};
module(function($provide){
$provide.value('varService', mockService);
});
inject(function($route, $location, $rootScope, $httpBackend) {
$httpBackend.expectGET('/services/main/html/main.html').respond({});
$location.path('/services/main');
$rootScope.$digest();
expect($route.current).toBeDefined();
});
});
});
this ensures the coverage for the resolve.

Resources