While going through the tutorial, i am coming across a strange scenario.
while injecting the service in your component if you miss the access modifier it will give you error as given below, but adding it as private or public will run fine.
Dont we have any default scope in Angular if we miss the access modifier ?
export class UserDetailsComponent implements OnInit {
name="";
lastName="";
constructor(userService : UserServiceService) { }
ngOnInit() {
}
save(){
this.userService.saveUser();
}
}
Property 'userService' does not exist on type 'UserDetailsComponent'.
while injecting the service in your component if you miss the access modifier it will give you error as given below, but adding it as private or public will run fine.
With an access modifier, you can define it as a class member, hence changing the scope to the class. Show activity on this post. When you do it without access modifier (which is local to the constructor function only), you need to then define that class property by yourself as in the second example.
You can limit the scope of an injected service to a branch of the application hierarchy by providing that service at the sub-root component for that branch.
Like methods, constructors can have any of the access modifiers: public, protected, private, or none (often called package or friendly). Unlike methods, constructors can take only access modifiers. Therefore, constructors cannot be abstract , final , native , static , or synchronized .
If you prefix a constructor parameter with an access modifier (private
, protected
or public
) or readonly
, it automatically gets "promoted" to be a class property in TypeScript. This construct is referred to as constructor parameter properties.
Without the prefix, the constructor parameter is nothing more than a method parameter, and you would have to manually assign it to a declared class property from the constructor itself.
From the handbook:
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
, orreadonly
. The resulting field gets those modifier(s):
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