How to set data to the injected service's property in library's service. Service injected using InjectionToken

Viewed 9

I want to set the value to data property of FirstAppService injected using Injection token @Inject(APP_SERVICE) private appService: FirstAppServiceInterface.

I set the value from printfromService method of FirstLibraryService

// FirstLibraryService in library package

import { Inject, Injectable, InjectionToken } from '@angular/core';

export interface FirstAppServiceInterface {
  data: string;
  printAppData(data:string): void;
}

export const APP_SERVICE = new InjectionToken<FirstAppServiceInterface>(  'appservice');

@Injectable({
  providedIn: 'root',
})
export class FirstLibraryService {
  constructor(
    @Inject(APP_SERVICE) private appService: FirstAppServiceInterface
  ) {}

  printfromService() {    
    this.appService.data = 'somevalue'
    console.log(this.appService.data) // it is giving undefined
  }

  newprint(){
    console.log('444',this.appService.data)
  }
}
// AppComponent

import { Component } from '@angular/core';
import { FirstLibraryService } from 'first-library';
import { FirstAppService } from 'src/firstApp.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'firstApp';

  constructor(private firstLibraryserv: FirstLibraryService){
        // this.appservice.data = 'Set by App'
  }


  printFromLib(){   
    this.firstLibraryserv.printfromService()
  }

  printFromApp(){
    // this.appservice.printAppData()
  }


}

// AppModule

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { APP_SERVICE, FirstLibraryService } from 'first-library';
import { FirstAppService } from 'src/firstApp.service';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule],
  providers: [
    FirstLibraryService,   
    {
      provide: APP_SERVICE, // Here it is injected 
      useExisting: FirstAppService,
    },
  ],
  bootstrap: [AppComponent],
})
export class AppModule {}


0 Answers
Related