Ways to identify modifications from a BehaviorSubject and automatically trigger a response according to the updated value

I am currently implementing a BehaviorSubject for managing languages in my Angular project. I am also utilizing Angular Datatables and trying to dynamically change the language displayed in the data table based on the value returned from the subscription. Is there a way to accomplish this seamlessly?

Thank you in advance.

// Service

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class SharedService {
  public lang = new BehaviorSubject<string>('en');
}

In the Component :

 ngOnInit(): void {
    // get language
    this.langServiceSupscribtion = this.sharedService.lang.subscribe((l) => {
      this.lang = l;
    });

    this.dtOptions = {
      pagingType: 'full_numbers',
      language: {
        paginate: {
          first: this.lang == 'ar' ? 'الأول' : 'First',
          previous: this.lang == 'ar' ? 'السابق' : 'Previous',
          next: this.lang == 'ar' ? 'التالي' : 'Next',
          last: this.lang == 'ar' ? 'الأخير' : 'Last',
        },
        search: this.lang == 'ar' ? 'ابحث:' : 'Search:',
        info:
          this.lang == 'ar'
            ? 'إظهار _START_ إلى _END_ من _TOTAL_ مدخلات'
            : 'Showing _START_ to _END_ of _TOTAL_ entries',
        lengthMenu:
          this.lang == 'ar' ? 'عرض _MENU_ مدخلات' : 'Show _MENU_ entries',
        emptyTable:
          this.lang == 'ar'
            ? 'لا يوجد بيانات متاحة في الجدول'
            : 'No data available in table',
        zeroRecords:
          this.lang == 'ar'
            ? 'لم يعثر على أية سجلات'
            : 'No matching records found',
        infoEmpty:
          this.lang == 'ar'
            ? 'إظهار 0 إلى 0 من أصل 0 مدخلات'
            : 'Showing 0 to 0 of 0 entries',
        processing: this.lang == 'ar' ? 'جارٍ المعالجة...' : 'Processing...',
      },
    };
}

Answer №1

To start, make sure to update your options within the subscribe function.

ngOnInit(): void {
    this.langServiceSupscribtion = this.sharedService.lang.subscribe((l) => {
        this.lang = l;
        this.updateOptions();
    });
}
updateOptions() {
    this.dtOptions = {
        pagingType: 'full_numbers',
        language: {
            paginate: {
                first: this.lang == 'ar' ? 'الأول' : 'First',
                previous: this.lang == 'ar' ? 'السابق' : 'Previous',
                next: this.lang == 'ar' ? 'التالي' : 'Next',
                last: this.lang == 'ar' ? 'الأخير' : 'Last',
            },
            search: this.lang == 'ar' ? 'ابحث:' : 'Search:',
            info: this.lang == 'ar' ?
                'إظهار _START_ إلى _END_ من _TOTAL_ مدخلات' :
                'Showing _START_ to _END_ of _TOTAL_ entries',
            lengthMenu: this.lang == 'ar' ? 'عرض _MENU_ مدخلات' : 'Show _MENU_ entries',
            emptyTable: this.lang == 'ar' ?
                'لا يوجد بيانات متاحة في الجدول' :
                'No data available in table',
            zeroRecords: this.lang == 'ar' ?
                'لم يعثر على أية سجلات' :
                'No matching records found',
            infoEmpty: this.lang == 'ar' ?
                'إظهار 0 إلى 0 من أصل 0 مدخلات' :
                'Showing 0 to 0 of 0 entries',
            processing: this.lang == 'ar' ? 'جارٍ المعالجة...' : 'Processing...',
        },
    };
    this.rerender() // Create a rerender function based on the angular-datatables example.
}

Your implementation seems correct, but it's important to remember to re-render your table after updating options. Refer to this page for guidance on how to re-render your table:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

problem with arranging sequences in angular highcharts

I am facing an issue with sorting points in different series using highcharts. To illustrate my problem, consider the following example series: [ {name: 'series one', value: 5 values}, {name: 'series two', value: 10 values} ] When usin ...

Error: Angular router outlet could not find any matching routes for the requested

I have been working on an application that utilizes lazy-loaded modules for each main section of the app. In one module, I have two router outlets - a primary one and one called details. const routes: Routes = [ { path: '', component: BooksCo ...

Passing a class as a parameter in Typescript functions

When working with Angular 2 testing utilities, I usually follow this process: fixture = TestBed.createComponent(EditableValueComponent); The EditableValueComponent is just a standard component class that I use. I am curious about the inner workings: st ...

the object '[object Object]' of a distinct supporting nature

I encountered an error stating "ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays." This is my TypeScript file: this.list = data.json(); ...

Facing issues with integrating Mixpanel with NestJS as the tracking function cannot be located

While utilizing mixpanel node (yarn add mixpanel) in conjunction with NestJS, I have encountered an issue where only the init function is recognized. Despite calling this function, I am unable to invoke the track function and receive the error message: Ty ...

Retrieve all services within a Fargate Cluster using AWS CDK

Is there a way to retrieve all Services using the Cluster construct in AWS CDK (example in TypeScript but any language)? Here is an example: import { Cluster, FargateService } from '@aws-cdk/aws-ecs'; private updateClusterServices(cluster: Clus ...

Cache for JSON Schema in VS Code

After updating to TypeScript 1.5 (now out of beta), I am eager to utilize the json schema helpers in VS Code. Upon configuring tsconfig.json, I noticed that only commonjs and amd module options are available, while umd and system are missing based on this ...

Remove observableB if it is triggered 1 second after observableA

Imagine having two different observables, known as observableA and observableB. There are 3 possible scenarios for how these observables can be activated: only observableA is activated. only observableB is activated. observableA is activated first, follo ...

What sets apart a class from a service in NativeScript?

I am embarking on the journey of learning Nativescript + Angular2, and while reading through the tutorial, I came across this interesting snippet: We’ll build this functionality as an Angular service, which is Angular’s mechanism for reusable classes ...

Having trouble performing nested queries with RxJS 6 and the expand operator in Angular, Firebase, and Observables?

I came across a query on Stack Overflow that helped me fetch a random item from a Firebase collection in my Angular 9 app using AngularFire. While the solution works perfectly and gives me the desired output most of the time, there's an issue when th ...

What is the best way to specify the return type in TypeScript when there is a possibility of multiple types?

I'm currently working on implementing type definitions for an Axios API client but I’m struggling with indicating to the compiler the specific return type that I am expecting. Here is a simplified example: import axios, { AxiosResponse } from "axi ...

Can users define their own customized shortcut keys in the web application?

I'm working on a web application built with Angular 7.0 and Node.js. I'm looking to implement a shortcut engine similar to Microsoft Word, where users can customize or modify default shortcut keys for certain functions in the app. Are there any c ...

Express is experiencing issues with Angular Universal, preventing it from functioning properly

While attempting to implement Angular Universal in my project, I encountered some issues. Here are the details: 1. ng --version Angular CLI: 9.0.2 Node: 13.5.0 OS: win32 x64 Angular: 9.0.1 ... animations, common, compiler, compiler-cli, core, forms ... ...

Issue with Angular FormControl Pattern Validator failing to validate against regex pattern

My goal is to restrict a text input field to specific characters only. I am looking to allow: alphanumeric characters (a-z A-Z 0-9) 3 special characters (comma, dash, single quotation mark) : , - ' A few accented characters: à â ç è é ê î ô ...

Setting up a service endpoint for an Angular 4/5 application

Operating an Angular 4 application with a web API data service requires unique configuration for each of the 100 customers utilizing this setup. Each customer hosts their own version of the data service and Angular application on their IIS server, meanin ...

In what scenarios would it be more advantageous to utilize ngStyle over creating a custom directive?

I had the need to dynamically change the width of a column, so I created a unique custom directive for that specific purpose: @Directive({ selector: '[rq-column-size]' }) export class ColumnSizeDirective { @Input('rq-column-size') ...

Using the Post method in Angular will result in a 400 status code being returned

I am a student developer working with the Angular platform. I have my own API and a post method that looks like this: [HttpPost] [Route("login")] public async Task<ActionResult<User>> LoginUser([FromBody] User _user) { var joinedUser = _co ...

Customize the style of Angular Material within an Angular component

In my Angular component, I am utilizing Material 2's <md-input-container>. I am looking to customize a specific class, such as .mat-input-wrapper, that is originally defined in Angular Material. However, my intention is for this customization to ...

Can you explain the significance of the "@" symbol prefix found in npm package names?

While reading through the Angular Component Router documentation, I came across an npm command that caught my attention: npm install @angular/router --save I'm puzzled by the meaning of @angular/router. Is this entire string a package name? If so, ...

Utilizing getters and setters with v-model in a class-based component: A step-by-step guide

Transitioning from an angular background to vuejs has been challenging for me as a newbie. I've encountered issues while trying to bind setter/getter in v-model for an input field. Interestingly, when I directly bind it to a variable, everything works ...