How to write a factory in ionic 2?

in ionic 1, we wrote factories in app.js file, something like this:

.factory(‘AuthenticationService’, [‘Base64’, ‘$http’, ‘$rootScope’, ‘$timeout’, ‘$window’, ‘$state’,’$ionicHistory’,
function(Base64, $http, $rootScope, $timeout, $window, $state, $ionicHistory) {
//content here
});

how to write this in ionic 2?

It’s easy, I wrote an article on this topic, find it here: http://www.gajotres.net/ionic-2-sharing-data-between-pagescomponents/

Technically, what was factory in Angular1 is now just a basic class (just without HTML part/template).

For example, this is a class from my example:

export class ShareService {  
 
	constructor() {
			this.firstName = 'Blank';
			this.lastName = 'Name';
	}
			 
	setFirstLastName(firstName, lastName) {
			this.firstName = firstName;
			this.lastName = lastName;       
	}
			 
	getFirstName() {
			return this.firstName + ' ' + this.lastName;
	}   

	getLastName() {
			return this.firstName + ' ' + this.lastName;
	}   
}

If you want to use it just import it in app.js:

import {ShareService} from './pages/services/ShareService';

Then initialize it like this:

@App({
	templateUrl: 'build/app.html',
	providers: [ShareService]
})

The last step should be done only in app.js, it will then be available to all child components/pages.

In child components/pages you must only include it:

import {ShareService} from '../services/ShareService';

Working example can be found in a provided article.

1 Like

Hi @Gajotres,

If I create my own ‘ExampleService’, then do import {ExampleService} from './providers/example.service', I need to add it to the app’s providers array to register the provider with the dependency injector, which makes me wonder…

How are angular’s core injectables initialised?

For example, it is possible to just do import {Http} from 'angular2/http' and then inject a constructor(http: Http) parameter into a service or wherever without having to do the provider initialising.

I have been looking through some of the angular source code and can’t seem to figure it out and wonder if you knew the answer to this?

Thanks!

I think, ionic provides it through bootstrap. (root level of Angular 2 application)

Ah right! So Ionic passes in all of angular providers somehow to the app bootstrap function?

Do you know where this is done? Just curious to see what is going on! :slight_smile:

node_modules/ionic-angular/bundles/ionic.system.js :1807