Constructor in Ionic

A newbiw question about the constractor in Ionic V2

Why do we need to inject any services that we
want to use inside of the class into the constructor like this?

constructor(platform: Platform, nav: NavController) {

}

Why not simply declaring the platform: Platform and nav: NavController as Class member variables wont work? Aren’t they instantiated too when class is created?

Just as normal variables:

rootPage:any = HomePage;
someVariable: String= “hey!”;

I ask because I didn’t see the need of a class declared in Ionic to be declared with the new keyword like:

HomePage homepage = new HomePage (platform, nav);

I thought the main use of constractor is to instantiate the class with variables we pass when
we create new instance of the class.

because you have to inject dependency, this is a design pattern

2 Likes

Exctly. Angular by default injects the imported classes, but you can choose to inject something else when you manually create an instance of this class (in testing for example, and then you can inject a Mock instead of the real Platform).

(Vocabulary in this post is probably not 100% accurate, but I hope you get the idea)

1 Like