Powered by Blogger.

Services in Angular js

Services in Angularjs can be created by 3 ways.

1) Creating services with the Factory
angular.module("MyApp").factory("MedisoftFactory", function($http) {
var factory = {};
var groupList = [{
id : 'patientName',
label : 'Patient Name'
}, {
id : 'billDate',
label : 'Bill Date'
}, {
id : 'typeName',
label : 'Type'
}, {
id : 'subTypename',
label : 'Sub Type'
}];

factory.getGroupList = function() {
return groupList;
}
return factory;
});


Creating services with the service
There are other ways to create services with AngularJS, but hold on, you might be thinking "why should we consider this choice if we have already used the factory?"
Basically, this decision is all about design. The service is very similar to the factory;
however, instead of returning a factory function, it uses a constructor function, which is equivalent to using the new operator.
In the following code, we created our parkingService method using a constructor function:
services.js
parking.service("parkingService", function (parkingConfig) {
this.calculateTicket = function (car) {
var departHour = new Date().getHours();
var entranceHour = car.entrance.getHours();
var parkingPeriod = departHour – entranceHour;
var parkingPrice = parkingPeriod * parkingConfig.parkingRate;
return {
period: parkingPeriod,
price: parkingPrice
};
};
});

Also, the framework allows us to create services in a more complex and configurable way using the provider function.


Creating services with the provider
Sometimes, it might be interesting to create configurable services. They are called providers, and despite being more complex to create, they can be configured before being available to be injected inside other components.
While the factory works by returning an object and the service with the constructor function, the provider relies on the $get function to expose its behavior. This way, everything returned by this function becomes available through the dependency injection.
In the following code, we refactored our service to be implemented by a provider. Inside the $get function, the calculateTicket method is being returned and will be accessible externally.
services.js
parking.provider("parkingService", function (parkingConfig) {
var _parkingRate = parkingConfig.parkingRate;
var _calculateTicket = function (car) {
var departHour = new Date().getHours();
var entranceHour = car.entrance.getHours();
var parkingPeriod = departHour – entranceHour;
var parkingPrice = parkingPeriod * _parkingRate;
return {
period: parkingPeriod,
price: parkingPrice
};
};
this.setParkingRate = function (rate) {
_parkingRate = rate;
};
this.$get = function () {
return {
calculateTicket: _calculateTicket
};
};
});

In order to configure our provider, we need to use the config function of the Module API, injecting the service through its function.

Setting values
In the following code, we are calling the setParkingRate method of the provider, overwriting the default rate that comes from the parkingConfig method.
config.js
parking.config(function (parkingServiceProvider) {
parkingServiceProvider.setParkingRate(10);
});

The other service components such as constants, values, factories, and services are implemented on the top of the provider component, offering developers a simpler way of interaction.

Success and failure on Ajax call
We can attach the success and error behavior:
$http({method: "GET", url: "/resource"})
.success(function (data, status, headers, config, statusText) {
})
.error(function (data, status, headers, config, statusText) {

});

Ajax call in angularjs
To make it easier to use, the following shortcut methods are available for this service.
In this case, the configuration object is optional:
$http.get(url, [config])
$http.post(url, data, [config])
$http.put(url, data, [config])
$http.head(url, [config])
$http.delete(url, [config])
$http.jsonp(url, [config])

Example:-
var retrieveCars = function () {
$http.get("/cars")
.success(function(data, status, headers, config) {
$scope.cars = data;
})
.error(function(data, status, headers, config) {
switch(status) {
case 401: {
$scope.message = "You must be authenticated!"
break;
}
case 500: {
$scope.message = "Something went wrong!";
break;
}
}
console.log(data, status);
});
};

The success and error methods are called asynchronously when the server returns the HTTP request.

Caching
To improve the performance of our application, we can turn on the framework's caching mechanism. It will store each response from the server, returning the same
result every time the same request is made.
However, take care. Some applications demand updated data, and the caching mechanism may introduce some undesired behavior. In the following code, we are enabling the cache mechanism:

parking.run(function ($http) {
$http.defaults.cache = true;
});



parking.run(function ($rootScope) {
$rootScope.$on("$routeChangeStart", function(event, current,previous, rejection)) {
$rootScope.loading = true;
});
});
parking.run(function ($rootScope) {
$rootScope.$on("$routeChangeSuccess", function(event, current,previous, rejection)) {
$rootScope.loading = false;
});
});
parking.run(function ($rootScope, $window) {
$rootScope.$on("$routeChangeError", function(event, current,previous, rejection) {
$window.location.href = "error.html";
});
});


parking.controller('parkingController', function ($scope, $log) {
$log.info('Entered inside the controller');
});

$watch:- The basics are that you can call $watch() with an expression to observe and a callback that gets invoked whenever that expression changes.

var myapp = angular.module("MyApp", []);
myapp.controller("StartUpController",function($scope){
    $scope.funding = {startingEstimate: 0};
    $scope.computeNeeded = function () {
        $scope.funding.needed = $scope.funding.startingEstimate * 10;
    };
    $scope.$watch('funding.startingEstimate', $scope.computeNeeded);
});


Remove items from List
$scope.items = [
{title: 'Paint pots', quantity: 8, price: 3.95},
{title: 'Polka dots', quantity: 17, price: 12.95},
{title: 'Pebbles', quantity: 5, price: 6.95}
];

$scope.remove = function(index) {
$scope.items.splice(index, 1);
}

<div ng-repeat='item in items'>
      <span>{{item.title}}</span>
      <input ng-model='item.quantity'>
      <span>{{item.price | currency}}</span>
      <span>{{item.price * item.quantity | currency}}</span>
      <button ng-click="remove($index)">Remove</button>
</div>

Add Items in List
$scope.students = [
      {name:'Mary Contrary', id:'1'},
      {name:'Jack Sprat', id:'2'},
      {name:'Jill Hill', id:'3'}];
$scope.insertTom = function () {
      $scope.students.splice(1, 0, {name:'Tom Thumb', id:'4'});
};

<div ng-controller='StartUpController'>
<ul>
    <li ng-repeat='student in students'>
        <a href='/student/view/{{student.id}}'>{{student.name}}</a>
    </li>
</ul>
<button ng-click="insertTom()">Insert</button>
</div>







0 comments:

Recent Articles

© 2014 Learning Java. WP themonic converted by Bloggertheme9. Published By Gooyaabi Templates
TOP