Services and Injectable in Angular

Points to remember while creating a service in Angular

  • First create a service first using the command “ng generate service serviceName”
  • Note the above class should have @Injectable annotation above the class.
  • Now in the class where you need to use this service you need to pass a private reference of that class “constructor(private serviceVar: serviceName){}”
  • Now we need to add the service name in the provider section of the @Component so that the instance of the service is created while the constructor is called.
  • Now you can call the service method inside the class using “this.serviceVar.method()”

Leave a Comment