Quantcast
Channel: Ionic Forum - Latest posts
Viewing all articles
Browse latest Browse all 228595

How to write a factory in ionic 2?

$
0
0

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.


Viewing all articles
Browse latest Browse all 228595

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>