0

I have a service which populates its fields values in Constructor. But I want the service's fields values to be updated whenever the service is invoked:

service.ts:

@Injectable()
export class MyDefaultIntl extends OwlDateTimeIntl {

    rangeFromLabel = '';

    constructor(
      private translateService: TranslationService,
    ) {
      super();
      console.log('service is constructed');
      this.subscribeToTranslations();
    }

    subscribeToTranslations(): void {
      this.translateService
        .translateKey('FROM_LABEL')
        .subscribe(message => {
          console.log('From Message:' + message);
          this.rangeFromLabel = message;
        });
    }
}

In my module.ts:

@NgModule({
  imports: [OwlDateTimeModule,OwlNativeDateTimeModule],
  exports: [OwlDateTimeModule,OwlNativeDateTimeModule],
  providers: [
    {provide: OwlDateTimeIntl, useClass: MyDefaultIntl},
  ],
})

translation service:

@Injectable()
export class TranslationService {
    constructor(private translate: TranslateService) {
    }
    translateKey(key: string, param?: any){
          return this.translate.get(key, param);
    }
}

Now what happens is the Constructor is called just once, and never constructed again (i.e. it never gets destroyed so that it can be constructed again).

Due to this, the rangeFromLabel value does not change later in the application because the service constructor is not called.

Is there any way to change the field value at later stages after the service is constructed?

Or is there any way to destroy the service and reconstruct it?

I've added the service in the providers provide section, and not the component's providers section. Will this make any change?

user5155835
  • 2,890
  • 2
  • 24
  • 64

1 Answers1

0

your rangeFromLabel doesn't depends upon constructor call as it's receiving the values from observable and because you already subscribed to object in first call it will get change on each event emitted by observable you don't need to subscribe on each call

this.translateService
        .translateKey('FROM_LABEL')
        .subscribe(message => {
          console.log('From Message:' + message);//it will get called evrytime observable event is emitted
          this.rangeFromLabel = message;
        });
jitender
  • 8,148
  • 1
  • 16
  • 41
  • The translateKey method has to be called always to get the updated value. I've also updated my question with the code of translation service. – user5155835 Oct 11 '19 at 10:27
  • as per doc **There are two ways to make a service a singleton in Angular Declare root for the value of the @Injectable() providedIn property Include the service in the AppModule or in a module that is only imported by the AppModule** first one is fine as you don't add providedIn can you check for the second case that may be the reason – jitender Oct 11 '19 at 10:33