Skip to content

Instantly share code, notes, and snippets.

@sarfarazansari
Last active February 14, 2017 05:15
Show Gist options
  • Save sarfarazansari/cf981dcc8b9fb98f615001ceb0056947 to your computer and use it in GitHub Desktop.
Save sarfarazansari/cf981dcc8b9fb98f615001ceb0056947 to your computer and use it in GitHub Desktop.
Factory example for ECMA+Angular
export function SimpleGithubUser ($http) {
'ngInject';
var apiUrl = 'https://api.github.com/';
// instantiate our initial object
var SimpleGithubUser = function(username) {
this.username = username;
this.profile = this.getProfile();
};
// define the getProfile method which will fetch data
// from GH API and *returns* a promise
SimpleGithubUser.prototype.getProfile = function() {
// Generally, javascript callbacks, like here the $http.get callback,
// change the value of the "this" variable inside it
// so we need to keep a reference to the current instance "this" :
var self = this;
return $http.get(apiUrl + 'users/' + this.username).then(function(response) {
// when we get the results we store the data in user.profile
self.profile = response.data
// promises success should always return something in order to allow chaining
return response;
});
};
return SimpleGithubUser;
}
//way to inject in app
import { SimpleGithubUser } from 'PATH_TO_FILE';
.factory('SimpleGithubUser', SimpleGithubUser)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment