I'm a .net programmer with littler experience in AngularJs
and Javascript
.
I have implemented an AlertService
, AlertsController
and Alerts
view for alerts/notifications in my system. PaymentService
is a service that uses the alert service to notify user of things.
Could you please give me any comments about my code?
Am I following best practises in AngularJs
and Javascript
?
Should I handle errors in my services?
Here is my code:
alertService.js
'use strict';
app.service('AlertService', function () {
var handlers = [];
this.subscribe = function (handler) {
handlers.push(handler);
}
this.success = function (message) {
pushAlert({ type: 'success', message: message });
};
this.info = function (message) {
pushAlert({ type: 'info', message: message });
};
this.warning = function (message) {
pushAlert({ type: 'warning', message: message });
};
this.danger = function (message) {
pushAlert({ type: 'danger', message: message });
};
function pushAlert(alert) {
handlers.forEach(function (handler) {
handler(alert);
});
}
});
alertsController.js
'use strict';
app.controller('AlertsController', ['$scope', 'AlertService', function ($scope, alertService) {
$scope.alerts = [];
alertService.subscribe(function (alert) {
$scope.alerts.push(alert);
});
$scope.closeAlert = function(index) {
$scope.alerts.splice(index, 1);
};
}]);
alerts.html
<div ng-controller="AlertsController">
<uib-alert ng-repeat="alert in alerts" type="{{alert.type}}" close="closeAlert($index)">{{alert.message}}</uib-alert>
</div>
paymentService.js
'use strict';
app.service('PaymentService', ['$http', 'AlertService',
function ($http, alertService) {
this.pay = function (id, paymentMethod, numberOfInstallments, creditCard, pin) {
return $http.post('/api/payment',
{
id: id,
paymentMethod: paymentMethod,
numberofInstallments: numberOfInstallments,
creditCard: creditCard,
pin: pin
})
.then(success, error);
function success() {
alertService.success('Payment confirmed.');
}
function error(response) {
alertService.success(response.data);
}
};
}
]);