Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HowTo use injected service in template (Angular2)

Tags:

angular

Component

templateUrl : 'home.html'
..
providers:      [NavService]
..    
private navService:     NavService,
..

Template

 <li *ngFor="let state of states; let i=index" 
[class.active]="navService.isCurrentState(state)">

<span class="name">{{navService[state].name}}</span>

does not seem to work, what am I missing here? How can I access my service in my component template?

like image 474
stevek-pro Avatar asked Jul 10 '16 17:07

stevek-pro


People also ask

How do you inject a service into a component?

The @Injectable() decorator defines a class as a service in Angular and allows Angular to inject it into a component as a dependency. Likewise, the @Injectable() decorator indicates that a component, class, pipe, or NgModule has a dependency on a service. The injector is the main mechanism.

How are the services injected to your application?

Services are wired together using a mechanism known as Dependency Injection (DI). We just need to have an injectable service class to be able to share these service methods to any consuming component. Also, DI in our Angular components/services can be implemented using either constructor or injector.

What does @inject do in Angular?

@Inject() is a manual mechanism for letting Angular know that a parameter must be injected. Injecting ChatWidget component to make the component behave like a singleton service so that the component state remain same across the app.

How do you implement a service?

Starting a service You can start a service from an activity or other application component by passing an Intent to startService() or startForegroundService() . The Android system calls the service's onStartCommand() method and passes it the Intent , which specifies which service to start.


2 Answers

The problem with your code is that you declared the service as private. According to the documentation ( angular.io/tutorial/toh-pt4 ): "the messageService property must be public because you're going to bind to it in the template". If you change it to public in costructor you can use the service inside the template.

like image 98
Antonio Galliani Avatar answered Sep 18 '22 19:09

Antonio Galliani


Every property defined within the component class can be used in the template.

First, you could check that you have the correct value for navService:

@Component({
  (...)
  providers: [NavService]
})
export class SomeComponent {
  constructor(public navService: NavService) {
    console.log(navService); // <----
  }
}
like image 33
Thierry Templier Avatar answered Sep 21 '22 19:09

Thierry Templier