Angular services with RxJS; decrapify your services.

Pete Mertz
Nov 4, 2015 · 3 min read
var rx = require('rx');function UserService() {}
var colors = [
‘red’,
‘orange’,
‘yellow’,
‘green’,
‘blue’,
‘indigo’,
‘purple’
];
var UserService = function() {
var self = this;

/* Variables */
self.user = new rx.Subject();

/* Functions */
self.refresh = refresh;

function refresh() {
self.user.onNext({
name: ‘Fake Name’,
favoriteColor: colors[Math.floor(Math.random() * colors.length)]
});
}
}
var userService = new UserService();userService.user.subscribe((user) => {
console.log('user updated:', user);
});
userService.refresh();
userService.refresh();
> user updated: { name: ‘Fake Name’, favoriteColor: ‘yellow’ }
> user updated: { name: ‘Fake Name’, favoriteColor: ‘purple’ }
function someAsynchronousServerUpdate(user, callback) {
if (user.favoriteColor !== 'purple') {
callback(new Error('y u no like purple?!'));
} else {
callback(null, user);
}
}
var UserService = function() {
var self = this;

/* Variables */
self.user = new rx.Subject();

/* Functions */
self.refresh = refresh;
self.update = update;

function refresh() {
self.user.onNext({
name: ‘Fake Name’,
favoriteColor: colors[Math.floor(Math.random() * colors.length)]
});
}
function update(_user) {
someAsychronousServerUpdate(_user, (err, _validatedUser) {
if (err) {
// Do your error handling here
} else {
self.user.onNext(_validatedUser)
}
}
}
}
function someAsynchronousServerUpdate(user, callback) {
if (user.favoriteColor !== 'purple') {
callback(new Error('y u no like purple?!'));
} else {
callback(null, user);
}
}
var UserService = function() {
var self = this;

/* Variables */
self.user = new rx.BehaviorSubject(null);

/* Functions */
self.refresh = refresh;
self.update = update;
/* Initialization Logic */
self.refresh();

function refresh() {
self.user.onNext({
name: ‘Fake Name’,
favoriteColor: colors[Math.floor(Math.random() * colors.length)]
});
}
function update(_user) {
someAsychronousServerUpdate(_user, (err, _validatedUser) {
if (err) {
// Do your error handling here
} else {
self.user.onNext(_validatedUser)
}
}
}
}

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade