How can I set an array as a property of an object using the Angular Subscribe method?

I'm attempting to retrieve array values from the en.json translation file in Angular and then bind them to an object property using the code snippet below.

Here is the TypeScript code:

  ngOnInit() {
    this.en = {
      dayNamesMin: this.translateSvc
                  .get(['calendar.day_names_min.Sun', 'calendar.day_names_min.Mon', 'calendar.day_names_min.Tue', 'calendar.day_names_min.Wed',
                    'calendar.day_names_min.Thu', 'calendar.day_names_min.Fri', 'calendar.day_names_min.Sat'])
                  .subscribe(translated => {
                    console.log(Object.keys(translated).map(key => translated[key]));
                    return Object.keys(translated).map(key => translated[key]);
                  })
    };
  };

The en.json file has the following structure:

{
    "calendar" : {
        "day_names_min": {
            "Sun": "SUN",
            "Mon": "MON",
            "Tue": "TUE",
            "Wed": "WED",
            "Thu": "THU",
            "Fri": "FRI",
            "Sat": "SAT"
        }
    }
}

I'm utilizing the ngx translator service to extract data from the en.json file, subscribe to it, and assign the value to the dayNamesMin property of the this.en object.

Although when I log the value Object.keys(translated).map(key => translated[key]); in the console, it correctly displays the array ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"]. Unfortunately, it doesn't seem to bind to the object's property dayNamesMin.

Any assistance would be greatly appreciated!

Answer №1

When working with asynchronous data using observables, it is recommended to assign values inside the subscription rather than assuming that the variable will be assigned when accessed. In this scenario, you can implement the following

ngOnInit() {
  this.translateSvc.
    .get([
      'calendar.day_names_min.Sun', 
      'calendar.day_names_min.Mon', 
      'calendar.day_names_min.Tue', 
      'calendar.day_names_min.Wed',
      'calendar.day_names_min.Thu', 
      'calendar.day_names_min.Fri', 
      'calendar.day_names_min.Sat'
    ])
    .subscribe(translated => {
      this.en = {
        dayNamesMin: Object.keys(translated).map(key => translated[key])
      };
    });
}

It's important to note that the this.en variable won't have a value until the this.translateSvc.get() observable emits. Thus, you must consider that this.en is asynchronous when accessed.

For more information on handling async data, check here.


Alternatively, if you only intend to utilize the this.en variable in the template for displaying values, you can map the output from this.translateSvc.get() using the RxJS map operator and leverage the Angular async pipe.

Controller

en$: Observable<any>;

ngOnInit() {
  this.en$ = this.translateSvc.     // <-- assign the observable
    .get([
      'calendar.day_names_min.Sun', 
      'calendar.day_names_min.Mon', 
      'calendar.day_names_min.Tue', 
      'calendar.day_names_min.Wed',
      'calendar.day_names_min.Thu', 
      'calendar.day_names_min.Fri', 
      'calendar.day_names_min.Sat'
    ])
    .pipe(       // <-- transform the response here
      map(translated => ({ dayNamesMin: Object.keys(translated).map(key => translated[key]) }))
    );
}

Template

<ng-container *ngIf="(en$ | async) as en">
  {{ en.dayNamesMin | json }}
  {{ en.dayNamesMin[0] }}
  ...
  <p *ngFor="let day of en.dayNamesMin">
    {{ day }}
  </p>
</ng-container>

Update: Use with PrimeNg calendar

As demonstrated in the second approach, use the RxJS map operator to structure it into the required object format and incorporate it as input in the HTML template.

<ng-container *ngIf="(en$ | async) as en">
  <p-calendar 
    dateFormat="dd/mm/yy" 
    [(ngModel)]="value" 
    [locale]="en">   <!-- utilize `en` from the async pipe -->
  </p-calendar>
</ng-container>

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

`Unable to update the checked prop in MUI switch component`

The value of RankPermission in the switchPermission function toggles from false to true, but for some reason, the MUI Switch component does not update in the browser. I haven't attempted any solutions yet and am unsure why it's not updating. I&ap ...

Optimize your Kendo components in Angular with this top-notch customization strategy

How can kendo components like grids and charts be styled in the best possible way while following recommended practices? My current methods of styling them are: 1 : Utilizing ng deep, host, however these approaches have been deprecated and are not consi ...

What could be causing the disappearance of the top and bottom lines in jquery datatable after the data details are

After setting up a screen with a jquery datatable that loads correctly, I noticed an issue. When I edit the details of a record and return to the table, only the row containing the table is visible. Here is my table declaration: $(document).ready(() => ...

Using ngFor in Angular 6 to create a table with rowspan functionality

Check out this functional code snippet Desire for the table layout: <table class="table table-bordered "> <thead> <tr id="first"> <th id="table-header"> <font color="white">No.</font> </th> <th id="table-hea ...

How to import an HTML file using TypeScript

I need to load an html file located in the same directory as the typescript file and return it from the function. public ...(... ) : angular.IHttpPromise<string> { ... return $http({ method: 'GET', url: &apos ...

Obtain the content of a clicked item on the following page using NextJs

I am currently working on a nextjs app that displays a list of 10 movies on the homepage, each with a Button / Link that leads to a specific page for that movie where all its content is shown. Initially, I tried adding the movie id to the Link like this: ...

What's the best way to alter an HTTP request response and conveniently retrieve it before sending it back from an Observable?

I am in the process of upgrading to Angular version 5. Previously, I was using @angular/http, but now I need to switch to @angular/common/http and utilize HttpClient. My current setup involves making HTTP requests in services, which makes them easy to reu ...

Having trouble showing JSON data with Ionic 2 and Xcode?

Extracting JSON data from a JSON file in my project and viewing it using "ionic serve" on my Mac has been successful. However, I am facing an issue after building for IOS in XCode. I import the generated project into XCode as usual, but the JSON data is no ...

In Angular and Jasmine, it is important to note that when multiple actions are included within an it() function, they

I'm currently working on a test to ensure that each INPUT field is not empty. I seem to be facing some challenges in writing this test, which could be due to my lack of experience or the limitations of Jasmine when it comes to handling multiple action ...

Demonstration of basic geometric shapes being generated using Forge Viewer Angular

Using the ng2-adsk-forge-viewer library in Angular 7, I am attempting to render a .dmg file within the browser and create a custom geometry on the view. After creating an Extension and adding the addToScene method, while the Extension runs successfully, I ...

Angular is throwing an error stating that the type '{ }[]' cannot be assigned to the type '[{ }]'

I'm in need of assistance and clarification regarding the error I encountered in my application... When I receive a JSON response from an API with some data that includes an array of products, I aim to extract these products (izdelki) from the array, ...

Issue with react-router-dom loader defer type issue

I attempted to troubleshoot the issue with data loading by incorporating defer in the loader function. I am unsure how to specify the postResponse type, which represents the actual response data. Even after experimenting with type casting and other m ...

Two-way data binding in Angular 2 is a powerful feature that allows for

My goal is to construct a parent component called Action, which includes two child components named Infos and Localisation. I want to connect the inputs of the children with the parent model. This is the model: export class Action{ title: string; ...

Tips on implementing zod schema types with remapped fields using the toZod method

I'm currently working on mapping a schema key to a different name in my database interface Country { isoCode: string, nameEn: string, nameDe: string, phone: string, bla: string } const CountryJson = { i ...

The pre-line white-space property is not functioning as anticipated in my CSS code

content: string; this.content = "There was an issue processing your request. Please try using the browser back button."; .content{ white-space: pre-line; } <div class="card-body text-center"> <span class="content"> {{ content }} </span& ...

Spring Boot - The Cross-Origin Resource Sharing filter is effective for handling GET requests, however it does not properly handle other

In my current project, I am working on a Spring Boot 2.2.5 application paired with an Angular 9 frontend. One of the challenges I have faced is configuring a CORS filter in the Spring Boot backend to allow any origin, headers, and requests. After thoroug ...

Error encountered while rendering content in an Angular template

I'm currently integrating ngx-carousel into my application. Interestingly, the carousel works perfectly when I manually input the data. However, when trying to fetch the data from the server, it fails to work as expected. Take a look at my code snip ...

I am seeking a method to display formatted document texts from a file located in the asset folder within an Angular HTML document as a pop-up

Text File Content -> <b>Test</b> Below is a snippet of Angular HTML I attempted: <embed src=".\assets\docs\about\BRANCH_MASTER.txt">--> <object data=".\assets\docs&bs ...

Having trouble with firebase admin code completions not functioning properly in vscode?

I've attempted to install the Typescript integration for Firebase using: npm install --save-dev @types/firebase Unfortunately, I have not had any success. The "firebase-admin" and "firebase-functions" packages do not provide code completion or intel ...

Determining the Right Version of a Framework in npm: A Guide

One common issue I encounter is the uncertainty of which versions of npm, Ionic, and other tools I should have installed. It often goes like this: "Oh, there's a new version of the Ionic CLI out. Let's update." I install CLI v3.9.0. ...