Angular : How to Inject Nested Service in Component

How to Inject Nested Services in Component

Let's create a service url.service.ts that will will be injected in other services.


import { Injectable } from '@angular/core';

@Injectable()
export class UrlService{
    // business logic
}

Now lets create another service http.service.ts that will Inject this service.

import { UrlService } from './url.service.ts';

export class HttpService extends UrlService{
    // business logic
}

Now, we need to inject the HttpService in some component to make http calls. So now we can inject the HttpService in component as shown below.

import { Component ,OnInit } from '@angular/core';

import { UrlService } from './url.service.ts';
import { HttpService } from './http.service.ts';


@Component({
    selector : 'some-selector',
    templateUrl : 'some.html',
    providers: [HttpService, UrlService]
})
export class SomeComponent implements OnInit{
     // business logic
    constructor(private httpService:HttpService){
        // do something
    }

    ngOnInit(): void {
     
    }
    
}
Note

So, the important point to note here is we have provided both UrlService and HttpService in the provides but only the HttpService in the constructor.

You need to add all the services in the providers array of the Component but add only the service you want to the constructor.


No comments:

Powered by Blogger.