Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
828 views
in Technique[技术] by (71.8m points)

angular - Typescript dependency injection public vs private

What is the difference between injecting service with public and private.I see most of examples use private keyword in angular component. Would it have any implications of using public? e.g.

constructor(public carService: CarService) { }

vs.

constructor(private carService: CarService) { }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In addition to the prior answer ... anything marked as private cannot be accessed by the component's template either. (Private members can be accessed when using JIT, such as at development time, but not when using AOT, such as for production.)

So in your template, you could only do *ngIf='carService.isValid' if the injected service was marked as public.

But actually, best practice is to wrap any service properties/methods in a component property/method anyway and have the template bind to/call the component's property or method.

Something like this:

   get isValid(): boolean {
      return this.carService.isValid;
   }

And then access it like this: *ngIf='isValid'


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...