AngularJS Services

Services should contain
- HTTP requests made to the server
- Any code that has to do with retrieving raw data
Why data should not belong in the controller
- Controllers are thrown away after each new view is rendered
- There would be a lot of duplicate functionality
Services are singletons
- There is only one instance of a given service to be used across the entire Angular app
- Think of a service as a single point of access to specific data
Services are lazily loaded
- Angular will only instantiate a service when it is needed
- Angular would not need to reload the same service after that
Types of services
- Provider - Can use providers in .config()
- Factory - An injectable function
- Service - An injectable constructor
- Value - Like constants, but can't be injected in .config()
- Constant - Can be injected anywhere; value can never change
- All of these are providers; they are just ways of instantiating services
- You're best advised to use factories and the Revealing Module Pattern
Dependency Injection
- Specify only the modules that you need
- No need to worry in what order modules are defined
- Angular's $injector looks at parameter names
- Changing $http to $httpRequest would NOT work
- Minification of JS could break your Angular code
Solution to Minification
- Avoid implicit annotation:
-
- Use the $inject property annotation (better performance):
- Use inline array annotation (preferred by Angular):
app.controller('MyController', function($scope, MyService) {
// ...
});MyController.$inject = ["$scope", "$http", "MyService"];
function MyController($scope, $http, MyService) {
// code
}app.controller('MyController',
['$scope', 'MyService',
function ($scope, MyService) {
// code
}
]);The Angular $http service
- Facilitates communication with remote HTTP servers
- Return value of calling $http.get() or post() is a promise, so you can use the then() method
$http.get('/path')
Text
// Simple GET request example:
$http.get('/someUrl').
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});$http.post('/path', { })
Text
// Simple POST request example (passing data) :
$http.post('/someUrl', {msg:'hello word!'}).
success(function(data, status, headers, config) {
}).
error(function(data, status, headers, config) {
});Promises
- Represents the eventual result of an asynchronous operation
- Promises guarantee that something will run whether or not something succeeds execution
Promise Example
Transform your code from this:
fs.readFile("file.json", function(err, val) {
if( err ) {
console.error("unable to read file");
}
else {
try {
val = JSON.parse(val);
console.log(val.success);
}
catch( e ) {
console.error("invalid json in file");
}
}
});fs.readFileAsync("file.json")
.then(JSON.parse)
.then(function(val) {
console.log(val.success);
})
.catch(SyntaxError, function(e) {
console.error("invalid json in file");
})
.catch(function(e){
console.error("unable to read file")
});Into this:
Day-02 Angular 4.0
By Tarun Sharma
Day-02 Angular 4.0
- 849