Friday, March 20, 2020

Angular Service

Simpler way to make Angular service available to component, just add providedIn: 'root'

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


Then on consuming component:
@Component({
    selector: 'pm-products',
    templateUrl: './product-list.component.html'
    // no need to add provider
})
export class ProductListComponent {
    constructor(private _productService: ProductService)
}


To make it more explicit:

@Injectable()
export class ProductService {

Then on consuming component:
@Component({
    selector: 'pm-products',
    templateUrl: './product-list.component.html'
    providers: [ProductService] // explicitly add the service here
})
export class ProductListComponent {
    constructor(private _productService: ProductService)
}

No comments:

Post a Comment