Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6 : Use of access modifier while injection any service

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'.

like image 662
sparsh610 Avatar asked Oct 31 '18 01:10

sparsh610


People also ask

What happens when injecting a service without access modifier in Angular?

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.

What happens when you put an access modifier of a constructor parameter?

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.

How can we limit the scope of an injected service to a branch of the application hierarchy?

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.

Which constructor does not take access modifier or have parameters?

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 .


Video Answer


1 Answers

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, or readonly. The resulting field gets those modifier(s):

like image 159
Robby Cornelissen Avatar answered Sep 22 '22 04:09

Robby Cornelissen