Implement service manually

I have components B , C , D that inherit from class A

I want to use the service in class A , but I do not know how to implement it without introducing it from my children.

What I tried is the usual implementation: constructor(pageName: string = null, translate: TranslateService) { But when I do super() to create class A , an error is generated because I did not provide the second parameter.

Is there a way to embed in a parent class using Angular 2?

The version of Angular I am forced to use is: 2.2.1

EDIT:

A few examples: I have many pages, on each of which a loader can be displayed. Instead of entering the loader every time and managing the loader from each page, I want to do:

 export class BaseComponent { constructor(private loader: LoadingService) {} showLoading() { this.loader.show(); } } 

And then inherit from the component itself:

 @Component({ selector: "page-login", providers: [UsersService], templateUrl: "login.html" }) export class LoginPage extends BaseComponent { constructor(private usersService: UsersService) { super(); } } 

LoginPage has a showLoading method from it parent.

+22
angular
source share
1 answer

You can solve this problem using the service search service. This will easily allow you to get any service and use it in your parent classes without introducing them through your children (this can be a problem).

To use this, create a simple locator.service.ts class:

 import {Injector} from "@angular/core"; export class ServiceLocator { static injector: Injector; } 

Import this service into your app.module.ts :

 import {ServiceLocator} from './locator.service'; 

Then, in the constructor file of your module ( app.module.ts ?), Run this thing so that it can be used anywhere:

 export class AppModule { constructor(private injector: Injector){ // Create global Service Injector. ServiceLocator.injector = this.injector; } } 

Now, to use it in your superclass (your BaseComponent), just import the ServiceLocator

 import {ServiceLocator} from './locator.service'; 

and use it like:

 export class BaseComponent { public loader; constructor() { this.loader = ServiceLocator.injector.get(LoadingService) } showLoading() { this.loader.show(); } } 

Now you have embedded your service in an extensible parent element, and you can use it in child components without passing it to super ().

+43
source share

All Articles