As you may have read, or if you’ve ever heard me talking about Angular, you know I’m a big fan of John Papa’s Angular Style Guide. I definitely agree with so many things in his style guide and I try to follow them in my coding. One thing that I’ve found that I’ve started to do differently though is my usage of services over factories.
Recently, long time pair programmer and code reviewer, Ryan Martinsen came across some of my code and wondered what the hell I was doing. See, in John’s guide, he relies heavily on the Revealing Module Pattern (RMP) in order to define his factories. But since I switched to using services, I brought the RMP over with me. I define all my public service methods up top and then create them as named functions below. After describing what had happened, the response from Ryan was a “Oh, ok then.” which in my book is a MAJOR win!
Here’s an example of a RMP service:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
angular.module('blogpost.service',[]) | |
.service('BlogpostService',BlogpostService); | |
function BlogpostSerivce(){ | |
var service = this; | |
service.getBlogs = getBlogs; | |
service.createBlog = createBlog; | |
service.getBlogName = getBlogName; | |
////////// | |
var blogName = 'Test Blog'; | |
var blogs = ['blog1', 'blog 2', 'blog3']; | |
function getBlogs(){ | |
return blogs | |
} | |
function createBlog(blogObject){ | |
blogs.push(blogObject); | |
} | |
function getBlogName(){ | |
return blogName; | |
} | |
} |