How to call service in angularjs - javascript

(function() {
'use strict';
angular
.module('autocompleteCustomTemplateDemo', ['ngMaterial'])
.controller('DemoCtrl', DemoCtrl);
function DemoCtrl($timeout, $q, $log, $scope, $http) {
var self = this;
$scope.service_details = [];
$scope.productdetail == [];
$scope.add = function() {
$scope.show_servicelist = true;
$scope.type = function(e) {
alert(e);
}
$scope.service_details.push(JSON.parse($scope.productdetails));
}
self.simulateQuery = false;
self.isDisabled = false;
self.repos = loadAll();
self.querySearch = querySearch;
self.selectedItemChange = selectedItemChange;
self.searchTextChange = searchTextChange;
function querySearch(query) {
var results = query ? self.repos.filter(createFilterFor(query)) : self.repos,
deferred;
if (self.simulateQuery) {
deferred = $q.defer();
$timeout(function() {
deferred.resolve(results);
}, Math.random() * 1000, false);
return deferred.promise;
} else {
return results;
}
}
function searchTextChange(text) {
$log.info('Text changed to ' + text);
}
function selectedItemChange(item) {
$log.info('Item changed to ' + JSON.stringify(item));
$scope.productdetails = JSON.stringify(item);
}
function loadAll() {
var repos = [{
'product_gid': '1',
'product_name': 'stabilizer',
'forks': '16,175',
}, {
'product_gid': '2',
'product_name': 'stand',
'forks': '760',
}, {
'product_gid': '3',
'product_name': 'ac',
'forks': '1,241',
},
];
return repos.map(function(repo) {
repo.value = repo.product_name.toLowerCase();
return repo;
});
}
function createFilterFor(query) {
var lowercaseQuery = angular.lowercase(query);
return function filterFn(item) {
return (item.value.indexOf(lowercaseQuery) === 0);
};
}
}
})();
app.service("productservice", function($http) {
this.getproduct = function() {
deggure
var response = $http.get("/Productjson/");
return response;
}
});
I'm displaying angularjs file for listing autocomplete, now i have added new service file to get some data.I want to send the service data into app code, i dont know how to connect service with controller code.when i try to connect i got syntax error. please modify the code and guide me to fetch the service data .

This is full sample to show you how to use service in angularjs with controller:
var app = angular.module("app", []);
app.controller("ctrl", function($scope, service) {
$scope.alert = function() {
service.alert();
}
$scope.console = function() {
service.console();
}
})
app.service("service", function() {
this.alert = function() {
alert("hey")
}
this.console = function() {
console.log("hey")
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<button ng-click="alert()">alert</button>
<button ng-click="console()">console</button>
</div>

This is how you write a service-
I prefer factory:
(function() {
'use strict';
angular
.module('app')
.factory('productservice', productservice);
function productservice($q, $http) {
return {
getproduct : getproduct
};
function getproduct(){
var d = $q.defer();
$http({
method: 'GET',
url: 'url'
}).success(function(response){
d.resolve(response);
}).error(function(response){
d.reject(response);
});
return d.promise;
}
}
})();
Here;s controller
(function() {
'use strict';
angular
.module('app')
.controller('AppController', AppController);
function AppController(
$scope, productservice
) {
function getproduct(){
productservice.getproduct().then(function(response){
//got the response here
}, function(){
});
}
}
})();

Related

AngularJS update function is (still)not working

I have a function which updates the object, the problem is when I go back from the update form field to the detailed view, it initializes the old object instead of the updated object.
I want to populate the cars list in the CarService instead of the app.js
This is my carService:
window.app.service('CarService', ['HTTPService', '$q',
'$http', function (HTTPService, $q, $http) {
'use strict';
this.cars = [];
this.get = function () {
var deferred = $q.defer();
HTTPService.get('/car').then(function resolve(response) {
deferred.resolve(response.data);
}, function reject(response){
deferred.reject(response);
});
};
this.add = function (formCar) {
var deferred = $q.defer();
console.log("CarService response 1 : ");
$http.post('/#/car', formCar).then(function resolve(response){
deferred.resolve(response.data);
}, function reject(response){
deferred.reject(response);
});
return deferred.promise;
};
this.showDetails = function (carId){
var deferred = $q.defer();
$http.get('/car/view/{{carId}}').then(function resolve(response){
HTTPService.get('/car/view/' + carId).then(function
resolve(response) {
deferred.resolve(response.data);
}, function reject(response){
deferred.reject(response);
});
return deferred.promise;
};
this.put = function (carformUpdate, opleidingsprofielId) {
var deferred = $q.defer();
$http.put('/#/car/:carId/update', carformUpdate).then(function resolve(response){
deferred.resolve(response.data);
}, function reject(response){
deferred.reject(response);
});
return deferred.promise;
};
}]);
This is my updateCar controller:
window.app.controller('updateCarCtrl', ['$scope', '$routeParams',
'CarService', '$location', function ($scope, $routeParams, CarService,
$location) {
'use strict';
$scope.carId = $routeParams.carId;
initCar($scope.carId);
function initCar(carId) {
CarService.showDetails(carId).then(function success(car) {
$scope.car = car;
}, function error(response) {
});
}
$scope.updateCar = function (carId) {
carId = $scope.carId;
if($scope.car !== null){
CarService.put($scope.car, carId).then(function
success(response) {
$scope.car = response;
$location.path('/car/view/' + carId);
alert("Car updated");
}, function error(response) {
$scope.error = response.statusText;
$scope.myform = {};
});
}
};
}]);
This is my carView controller:
window.app.controller('carViewCtrl', ['$scope', '$routeParams', '$location',
'CarService', function ($scope, $routeParams, $location, CarService) {
'use strict';
$scope.carId = $routeParams.carId;
initCar($scope.carId);
function initCar(carId) {
CarService.showDetails(carId).then(function success(car) {
$scope.car = car;
}, function error(response) {
});
}
}]);
My carView initializes the object again when it gets redirected with $location.path('/car/view/' + carId); but as the original object and not the updated object.
I'm trying to do this on an ngMock backend.
My app.js looks like this:
App.js
routing:
.when('/car', {
templateUrl: 'pages/car/car.html'
})
.when('/car/view/:carId', {
templateUrl: 'pages/car/carView.html',
controller: 'carViewCtrl',
controllerAs: 'ctrl'
})
.when('/car/addCar', {
templateUrl: 'pages/car/carAdd.html'
})
.when('/car/:carId/update', {
templateUrl: 'pages/car/carUpdate.html',
controller: 'updateCarCtrl',
conrtollerAs: 'ctrl'
})
app.run: this is where my mock backend is defined
window.app.run(function($httpBackend) {
var cars = [
{
id: 0,
name: ‘car0’,
address: 'adress0',
tel: 'tel0',
email: 'email0'},
{
id: 1,
name: ‘car1’,
address: 'adress1',
tel: 'tel1',
email: 'email1'
}];
var carUrl = “/#/car”;
$httpBackend.whenGET(carUrl).respond(function(method,url,data) {
return [200, cars, {}];
});
$httpBackend.whenGET(/\/#\/car\/view\/(\d+)/, undefined,
['carId']).respond(function(method, url, data, headers, params) {
return [200, cars[Number(params.carId)], {
carId : params.carId
}];
});
$httpBackend.whenPUT('/#/car/:carId/update').respond(function(method, url,
data, carId) {
var car = angular.fromJson(data);
return [200, car, {}];
});
Thanks for any help!
It looks like your update function calls the CarService.put, which in turn calls a HTTPService.put. In your mocked backend you have this:
$httpBackend.whenPUT
-> add new car;
So it always adds a new car, and doesn't update one. This means that when you do the get, you probably get the first car back that matches the given id, which isn't the updated one.
In pseudo code:
// carService.cars = [{id:1,name:"name"}]
var myCar = carService.get(1); // returns {id:1,name:"name"}
myCar.name = "otherName";
carService.put(car); // -> cars.push(car); -> cars = [{id:1,name:"name"},{id:1,name:"otherName"}]
goToDetails(1);
var myCar = carService.get(1); // iterate over the cars, and return the one with id = 1,
// which is {id:1,name:"name"}

Send data through a POST request from Angular factory

I have this in the controller
angular.module('myApp')
.controller('TaskController', function ($scope, TaskFactory) {
$scope.addTodo = function () {
$scope.todos.push({text : $scope.formTodoText});
$scope.formTodoText = '';
};
});
and this in the factory
angular.module('myApp')
.factory('TaskFactory', function ($q, $http) {
var sendTasks = function(params) {
var defer = $q.defer();
console.log(1, params);
$http.post('http://localhost:3000/task/save', params)
.success(function(data) {
console.log(2);
console.log('data', data);
})
.error(function(err) {
defer.reject(err);
});
return defer.promise;
}
return {
sendTask: function(taskData) {
console.log('taskData', taskData);
return sendTasks('/task/save', {
taskData : taskData
})
}
}
});
all I need is to know, how to send the data from the controller to the factory in order to do the POST to the specified route ?
You just need to call the function/method inside factory with the required params.
angular.module('myApp')
.controller('TaskController', function ($scope, TaskFactory) {
$scope.addTodo = function () {
$scope.todos.push({text : $scope.formTodoText});
TaskFactory.sendTask({data : $scope.formTodoText})
$scope.formTodoText = '';
};
});
You can follow Dan Wahlin blog post.
Controller:
angular.module('customersApp')
.controller('customersController', ['$scope', 'dataFactory', function ($scope, dataFactory) {
$scope.status;
dataFactory.updateCustomer(cust)
.success(function () {
$scope.status = 'Updated Customer! Refreshing customer list.';
})
.error(function (error) {
$scope.status = 'Unable to update customer: ' + error.message;
});
}
Factory:
angular.module('customersApp')
.factory('dataFactory', ['$http', function($http) {
var urlBase = '/api/customers';
dataFactory.updateCustomer = function (cust) {
return $http.put(urlBase + '/' + cust.ID, cust)
};
}
Hope that solve your problem.
You can call the function directly on the TaskFactory that you pass into the controller as a dependency.
I've cleaned up your code a bit and created a plunk for you here:
And here's the code:
Controller
(function(angular) {
// Initialise our app
angular.module('myApp', [])
.controller('TaskController', function($scope, TaskFactory) {
// Initialise our variables
$scope.todos = [];
$scope.formTodoText = '';
$scope.addTodo = function() {
// Add an object to our array with a 'text' property
$scope.todos.push({
text: $scope.formTodoText
});
// Clear the input
$scope.formTodoText = '';
// Call function to send all tasks to our endpoint
$scope.sendTodos = function(){
TaskFactory.sendTasks($scope.todos);
}
};
});
})(angular);
Factory
(function(angular) {
angular.module('myApp')
.factory('TaskFactory', function($q, $http) {
var sendTasks = function(params) {
var defer = $q.defer();
$http.post('http://localhost:3000/task/save', params)
.success(function(data) {
console.log('data: ' + data);
})
.error(function(err) {
defer.reject(err);
});
return defer.promise;
}
return {
sendTasks: sendTasks
}
});
})(angular);

Angular service return undefined

I have a problem with my service in angular.
My service has the next code:
app.service("Utilidades", ['$http', '$window', function ($http, $window) {
return {
Get: function (urlAbsoluta, parametros, callback) {
var Utilidades = this;
$http
.get(app.UrlBase + urlAbsoluta, parametros)
.then(function (data) {
var Datos = angular.fromJson(data);
Utilidades.GuardarToken(Datos.Token);
callback(Datos);
});
},
ObtenerMenu: function () {
var Utilidades = this;
Utilidades.Get("Administracion/Api/Usuarios/Menu", {}, function (Datos) {
Datos = angular.fromJson(Datos.data);
if (Datos.Error == "") {
return Datos.Resultado;
} else {
return "";
}
});
}
}
}]);
Then, in my controller i have the next code:
app.controller('LoginCtrl', ['$scope', '$http', '$location', 'Utilidades',
function Iniciador($scope, $http, $location, Utilidades) {
var Li = this;
Li.Usuario = "";
Li.Contrasena = "";
Li.Error = "";
Li.MenuItems = [];
Li.Menu = function () {
Li. MenuItems = Utilidades.ObtenerMenu();
}
}]
);
When i run this, Li.MenuItems have undefined value and i don't know why.
Your return statements are in a function inside your ObtenerMenu method so the ObtenerMenu method is not actually returning anything. You need to provide a way to access the resulting value:
Service
app.service("Utilidades", ['$http', '$window', function ($http, $window) {
return {
Get: function (urlAbsoluta, parametros) {
var Utilidades = this;
// v------------ return statement here
return $http
.get(app.UrlBase + urlAbsoluta, parametros)
.then(function (data) {
var Datos = angular.fromJson(data);
Utilidades.GuardarToken(Datos.Token);
// v------------ return statement here
return Datos;
});
},
ObtenerMenu: function () {
var Utilidades = this;
// v------------ return statement here
return Utilidades.Get("Administracion/Api/Usuarios/Menu", {})
.then(function (Datos) {
if (Datos.Error == "") {
return Datos.Resultado;
} else {
return "";
}
});
}
};
}]);
In Controller
Li.Menu = function () {
Utilidades.ObtenerMenu()
.then(function (resultado) {
Li. MenuItems = resultado;
});
}
It's because ObtenerMenu function is asynchronous function. This function doesn't return anything initially (so undefined) and later, after some time when ajax request finishes, this function is already finished its execution stack

Why am I getting "Incorrect injection token!" in this angular application code?

I'm trying to setup a restful API interface via AngularJS with the following code:
'use strict';
(function(angular) {
function ApiAction($resource, ResourceParameters) {
return $resource(ResourceParameters.route,
{ },
{ api_index: {
method: ResourceParameters.method,
isArray: true
}
});
return $resource(ResourceParameters.route,
{ },
{ create: {
method: ResourceParameters.method,
isArray: true
}
}
);
}
function ResourceParameters($scope) {
var factory = {};
factory.method = '';
factory.route = '';
factory.SetMethod = function(method) {
factory.method = method;
}
factory.SetRoute = function(route) {
factory.route = route;
}
return factory;
}
function superheroCtr($scope, ApiAction, ResourceParameters) {
$scope.superheroSubmit = function() {
// ApiAction.create({}, { superhero_name: $scope.superheroName, age: $scope.superheroAge });
angular.forEach($scope.superheroes, function(hero) {
// ApiAction.create({}, { superhero_name: hero.superhero_name, age: hero.age });
});
};
var heroesResources = ResourceParameters($scope).SetRoute('/api/');
var heroes = ApiAction.api_index({}, heroesResources);
$scope.superheroes = [];
heroes.$promise.then(function(data) {
angular.forEach(data, function(item) {
$scope.superheroes.push(item);
});
}, function(data) {
//if error then...
});
$scope.appendSuperheroFields = function() {
var i = $scope.superheroes.length + 1;
$scope.superheroes.push({"id": i, age: "", superhero_name: "" })
}
}
var superheroApp = angular.module('superheroApp', ['ngResource']);
superheroApp.controller('superheroCtr', ['$scope', 'ApiAction', 'ResourceParameters', superheroCtr]);
superheroApp.factory('ResourceParameters', ['$scope', ResourceParameters]);
superheroApp.factory('ApiAction', ['$resource', ResourceParameters, ApiAction]);
})(angular);
Yet, when I run it I get the following error:
Error: [$injector:itkn] Incorrect injection token! Expected service name as string, got function ResourceParameters($scope)
Why is this?
Simply you can not inject $scope OR you can not have access to $scope
inside a factory
Your problem is at this line
superheroApp.factory('ResourceParameters', ['$scope', ResourceParameters]);
You need to replace that line with
superheroApp.factory('ResourceParameters', [ResourceParameters]);
Factory
function ResourceParameters() { //<--removed $scope from here
var factory = {};
factory.method = '';
factory.route = '';
factory.SetMethod = function(method) {
factory.method = method;
}
factory.SetRoute = function(route) {
factory.route = route;
}
return factory;
}
Update
Additionally you should correct the declaration of ApiAction where ResourceParameters should be placed inside ' single qoutes
superheroApp.factory('ApiAction', ['$resource', 'ResourceParameters', ApiAction]);

How to test a controller function calling a private function that in turn calls a asynchronous function in angularjs

[plunkr][1]http://plnkr.co/edit/Jk1Rp3nEgUQTmDOs3xBl?p=preview
My current code is structured as below.
angular.module("app",[])
.service("dataService",function($http){
this.get = function (url) {
return $http.get(url);
};
})
.service("mainService",function(dataService){
this.getData = function(pattern){
return dataService.get(pattern+"/abc");
}
})
.controller("mainController",function($scope,mainService){
$scope.refreshData = function(pattern){
loadData(pattern);
}
function loadData(pattern){
mainService.getData(pattern)
.success(function(data){
console.log(data);
})
.error(function(error){
console.log(error);
})
}
})
I have been trying to make sense of how to test it by reading blogs but each blog has either a different approach or the blog is 2-3 years old. I would like to know how do I test the controller?
Should I test each function? If yes, then how should I test the private function? Is using the private function a good idea or should I just add the private function code to the scoped function?
Also is there any better way to do write this function?
Most important part where we are going to create stub:
beforeEach(function() {
var $httpResponse = {
success: function() {
return $httpResponse;
},
error: function() {
return $httpResponse;
}
};
var _stubMainService_ = {
getData: jasmine.createSpy('getData').and.returnValue($httpResponse)
};
angular.module('app')
.value('mainService', _stubMainService_);
});
and test that uses it:
it('rereshes data', function() {
var pattern = 'abcde';
scope.refreshData(pattern);
expect(mainService.getData).toHaveBeenCalledWith(pattern);
});
angular.module("app", [])
.service("dataService", function($http) {
this.get = function(url) {
return $http.get(url);
};
})
.service("mainService", function(dataService) {
this.getData = function(pattern) {
return dataService.get(pattern + "/abc");
}
})
.controller("mainController", function($scope, mainService) {
$scope.refreshData = function(pattern) {
loadData(pattern);
}
function loadData(pattern) {
mainService.getData(pattern)
.success(function(data) {
console.log(data);
}).error(function(error) {
console.log(error);
})
}
})
describe('mainController()', function() {
var scope, controller, mainService, $q;
beforeEach(module('app'));
beforeEach(function() {
var $httpResponse = {
success: function() {
return $httpResponse;
},
error: function() {
return $httpResponse;
}
};
var _stubMainService_ = {
getData: jasmine.createSpy('getData').and.returnValue($httpResponse)
};
angular.module('app')
.value('mainService', _stubMainService_);
});
beforeEach(inject(function($controller, $rootScope, _mainService_) {
scope = $rootScope.$new();
controller = $controller('mainController', {
$scope: scope
});
mainService = _mainService_;
}));
it('rereshes data', function() {
var pattern = 'abcde';
scope.refreshData(pattern);
expect(mainService.getData).toHaveBeenCalledWith(pattern);
});
})
<link href="//safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine.css" rel="stylesheet" />
<script src="//safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine-2.0.3-concated.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular-mocks.js"></script>

Categories

Resources