I am learning Angular2
and working with classes
in javascript
first time.
What does the private
parameter and why it couldn't be simply heroService: HeroService
?
constructor(private heroService: HeroService) { }
Private Parameters are used internally, mainly to share a parameter value across multiple transformers. For example, multiple SchemaMappers may reference a single parameter for its schema mapping table dataset. You can also create parameters for username/password fields in commonly accessed database tables.
TypeScript Private PropertiesA private property of method can only be accessed or called from the class instance itself.
In TypeScript there are two ways to do this. The first option is to cast the object to any . The problem with this option is that you loose type safety and intellisense autocompletion. The second option is the intentional escape hatch.
Private methods/members are accessible only from inside the class. Protected methods/members are accessible from inside the class and extending class as well.
Looks like a parameter property. Basically, adding an access modifier (public/private/protected/readonly) to a constructor parameter will automatically assign that parameter to a field of the same name.
Specifically, from those docs:
TypeScript offers special syntax for turning a constructor parameter into a class property with the same name and value. These are called parameter properties and are created by prefixing a constructor argument with one of the visibility modifiers public, private, protected, or readonly. The resulting field gets those modifier(s)
So the following are equivalent:
class Foo { private bar: string; constructor(bar: string) { this.bar = bar; } } class Foo { constructor(private bar: string) {} }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With