0

I am using nrwl/nx. My project has 2 angular applications and 1 library. Inside this library, there are 1 component and 2 services. Both apps use the same component but with a different service.

How can I use the same component but with a different service?

The services have the same property keys, but not the same functionalities.

I was thinking about declaring a generic component like this post on StackOverflow: Declare a component with generic type I tried this. Here is the code:

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

@Component({
   selector: 'cms-login',
   templateUrl: './login.component.html',
   styleUrls: ['./login.component.scss']
})
export class BaseLoginComponent<T> implements OnInit {
   constructor(private loginService: T) { }

   ngOnInit(): void {
      this.loginService.getUser(); // tells property 'getUser()' does not exist in 'T'
   }
}

Here is the code from my services

@Injectable({
  providedIn: LoginModule
})
export class LoginService {
  private currentUserSubject: BehaviorSubject<UserEntity>;
  public currentUser: Observable<UserEntity>;

  public currentUserValue(): UserEntity {
    // different code
    return { id: 1, username: '' }
  }

  login(): Observable<any> {
    // different code
    return of(null);
  }

  logout() { }
}

I also was thinking about doing something with Dependency Injections, but I don't know how to implement it.

1 Answers1

1

You can try as follow

In library

  1. provide token

    export const TOKEN_API = new InjectionToken('api');

  2. provide interface

    interface IServiceInterface { }

  3. in component inject service by token

@Component({})
export class MyComponent {
  constructor(@Inject(TOKEN_API) private api: IServiceInterface) {
  }
}

In application you can provide dedicate service for injection token

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [
    { provide: TOKEN_API, useClass: MyServiceImplementation}
  ],
  bootstrap: [AppComponent]
})

//dedicate service
export class MyServiceImplementation implements IServiceInterface {
}
Radik
  • 2,715
  • 1
  • 19
  • 24