Type 'Observable<string> | undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string'

189 Views Asked by At

I was trying to translate a text in ts file using ngx-translate, but could not convert Observable to string data type.

I tried using this methods.

  1. this.endSession = this.translate.stream('sessions-info-view.end-sessions');

  2. this.endSession = JSON.stringify( this.translate.get('sessions-info-view.end-sessions') );

  3. this.endSession = this.translate.stream('session-info-view.end-sessions'). subscribe({ next:(data:string)=>{ debugger this.endSession=data;

    console.log(this.endSession) } }); All of them does not solve the issue. Here is the html code:

<app-context-menu
    id="contextForMenus"
    [contextMenuItems]="sessionInfoContextMenu"
    [showMenu]="isContextMenuOpened"
    [posX]="posX"
    [posY]="posY"
    (onContextMenuItemClick)="handleMenuItemClick($event)"
></app-context-menu>

Here is the ts file

constructor(public translate: TranslateService){
this.endSession = JSON.stringify(
      this.translate.get('sessions-info-view.end-sessions')
    );
}
import {TranslateService} from '@ngx-translate/core';

endSession = '';
sessionInfoContextMenu: ContextMenuModel = {
    endSession: {
      menuText: this.endSession,
      menuEvent: 'end_session',
      menuIcon: 'stop_circle',
      isDisabled: false,
      displayMenu: true,
      order: 0,
    },
    cancelOrders: {
      menuText: 'Cancel Orders',
      menuEvent: 'cancel_orders',
      menuIcon: 'cancel',
      isDisabled: true,
      displayMenu: false,
      order: 1,
    },
  };

sessions-info-view.end-sessions is a string value

1

There are 1 best solutions below

0
Yong Shun On

As the compilation error is clear, the TranslationService.get() returns an Observable<string>. To get the value, you are required to subscribe to the observable.

sessionInfoContextMenu: ContextMenuModel = {
  endSession: {
    menuText: '',
    menuEvent: 'end_session',
    menuIcon: 'stop_circle',
    isDisabled: false,
    displayMenu: true,
    order: 0,
  },
  cancelOrders: {
    menuText: 'Cancel Orders',
    menuEvent: 'cancel_orders',
    menuIcon: 'cancel',
    isDisabled: true,
    displayMenu: false,
    order: 1,
  },
};

ngOnInit() {
  this.translate.get('sessions-info-view.end-sessions')
    .subscribe((value: string) => {
      this.endSession = value;
      this.sessionInfoContextMenu.endSession.menuText = this.endSession;
    });
}