angularangular-library

How to use a service from a library project, which has some dependecy like toastr, in another angular library project


I have a one service in my library project which have dependency on toastr in my angular project

import { Injectable } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ToastrModule } from 'ngx-toastr';

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

  constructor(private toastr: ToastrService) { }
  showSuccess() {
    this.toastr.success('Hello world!', 'Toastr fun!');
  }
}

I already added the provider and also try to run without provider in my module of library. but still it is not working.

import { NgModule } from '@angular/core';
import { ComplCommonLibComponent } from './compl-common-lib.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ToastrModule } from 'ngx-toastr';
import {AlertService} from './services/alert.service';


@NgModule({
  declarations: [
    ComplCommonLibComponent
  ],
  imports: [
    BrowserAnimationsModule, 
    ToastrModule.forRoot()
  ],
  providers:[AlertService],
  exports: [
    ComplCommonLibComponent
  ]
})
export class ComplCommonLibModule { }

When I Use this in my consumer project. below is the consumer module

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ComplCommonLibModule } from 'compl-common-lib';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ToastrModule } from 'ngx-toastr';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    ToastrModule.forRoot(), 
    ComplCommonLibModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

below is the consumer component

import { Component } from '@angular/core';
import { AlertService } from 'compl-common-lib';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  standalone: false,
  styleUrl: './app.component.scss'
})
export class AppComponent {
  title = 'comp-autotn';
  constructor(private libService:AlertService){
    libService.showSuccess();
  }
}

I am getting error "Error: NG0203: inject() must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with runInInjectionContext."


Solution

  • I am not sure about the internal architecture, but after installation of native federation my issue is resolved.

    ng add @angular-architects/native-federation