1

Angular Services

 2 years ago
source link: https://www.hhutzler.de/blog/angular-services/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Providing a singleton service

Two ways to make a service singleton in Angular

  • Declare that the service should be provided in the application root.
  • Include the service in the AppModule or in a module that is only imported by the AppModule.

Beginning with Angular 6.0, the preferred way to create a singleton services is to specify on the service that it should be provided in the application root. This is done by setting providedIn to root on the service’s @Injectable decorator:

Prefered Angular 6 Way using @Injectable decorator

  • Angular creates a single, shared instance of service and injects into any class that asks for it.
  • Registering the provider in the @Injectable metadata also allows Angular to optimize an app by removing the service if it turns out not to be used after all.
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class VoteService {
}

Register Service in providers array of @NgModule

import {VoteService} from './vote.service';
...
@NgModule({
  imports:      [ BrowserModule],
  declarations: [ AppComponent],
  bootstrap:    [ AppComponent],
  providers: [VoteService]
})

Reference


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK