Exploring the Power of Observable Arrays in Angular 2

I am working with the code snippet below:

  get items():Observable<MenuItem[]>{

  let items: MenuItem[] =  [
      {
       label: "incidents_dialog_tab_actions_measures_defined"
      },
      {
       label: "incidents_dialog_tab_actions_measures_with_supplier_agreed"
      },
      {
        label: "incidents_dialog_tab_actions_measures_are_implemented"
      },
      {
        label: "incidents_dialog_tab_actions_measures_are_effective"
      }
  ];

  return  Observable.from(items).mergeMap( obj => this.commonModel.translate(obj.label)).bufferCount(items.length);
}

The method

this.commonModel.translate(obj.label)
in the code returns an observable.

In my template, I want to use it in the following way: [model]="items | async". Here, 'items' should be an observable of an array that contains translations in the format { label: translation}. How can I achieve this?

Answer №1

In order to properly transform the returned translation into the desired format, you must include a .map() method within this.commonModel.translate:

Observable.from(items)

 // Invoke the translation service for each item.
 .mergeMap(item =>
   this.commonModel.translate(item.label)
     // Save the translated result in an object with the specified format.
     .map(translatedLabel => ({ label: translatedLabel }))
 )

 // Reassemble all translated items back into one array.
 .toArray();

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

Converting Getters into JSON

I am working with a sequelize model named User that has a getter field: public get isExternalUser(): boolean { return this.externalLogins.length > 0; } After fetching the User from the database, I noticed in the debugger that the isExternalUser prop ...

What sets TypeScript apart from AtScript?

From what I understand, TypeScript was created by Microsoft and is used to dynamically generate JavaScript. I'm curious about the distinctions between TypeScript and AtScript. Which one would be more beneficial for a JavaScript developer to learn? ...

How can you eliminate the prop that is injected by a Higher Order Component (HOC) from the interface of the component it produces

In my attempt to create a Higher Order Component, I am working on injecting a function from the current context into a prop in the wrapped component while still maintaining the interfaces of Props. Here is how I wrap it: interface Props extends AsyncReque ...

Angular attribute directive encountered an error during production build, where it was expected to receive 1 argument but instead received

I have been working on a large-scale application that has been developed by multiple teams over an extended period. A frontend developer from another location included a significant amount of repetitive imperative code, utilizing jQuery for DOM manipulati ...

What is the best way to iterate over a nested array of objects and render them in my HTML using Angular/Ionic?

One of the challenges I'm facing involves working with an interface structured like this: export interface SeriesCard { type: string, imageUrl: string, title: string, category: string, seriesItems: SeriesItems[]; } Currently, my Service con ...

Converting a Promise to an Observable in Angular using Typescript

I have a working method that functions as intended: getdata(): Promise<any> { let query = `SELECT * FROM table`; return new Promise((resolve, reject) => { this.db.query(query, (error, rows) => { if(error) reject(error); ...

Repurpose existing views within an Angular 2+ component

There are times when I want to reuse certain views (HTML code) within a component without creating a new component. It would look something like this: <div *ngIf="Fordestop"> <div class="divdesktop"></div> #insert-my-reuse-div-he ...

Unable to retrieve data from response using promise in Angular 2?

I am struggling to extract the desired data from the response. Despite trying various methods, I can't seem to achieve the expected outcome. facebookLogin(): void { this.fb.login() .then((res: LoginResponse) => { this.acce ...

Ensuring type compatibility in a declarative manner: What are the methods?

My goal is to establish a compile-time constraint that ensures a variable of type T2 can be assigned to a variable of type T1. If I have a value (t2) of type T2, I can simply do the following: const t1: T1 = t2; Is there an alternative method to achiev ...

Unable to get Angular 6 project to run on IE and Edge browsers even though all necessary polyfill codes have been uncommented

https://i.sstatic.net/isXaa.pngHaving trouble running Angular 6 project on Edge and IE browsers, even though all necessary polyfill codes are uncommented. -> Encountering syntax errors when trying to open the site. ...

Creating shared modules for inter-library communication in NRWL

After setting up a nrwl workspace containing apps and libraries, I decided to centralize common resources in a Shared module. However, I encountered an issue with linting. The error message complains about the following: The 'libs/shared/services/s ...

Pass a boolean value using Angular2's routerLink functionality

Can't figure out how to pass a boolean value through a routerLink from a task-page to a team-page and use it in the HTML. Any ideas on what I might be doing wrong? This is how I've attempted it: <a [routerLink]="['/team', projectID ...

Encountering issues with installing angular/cli due to errors popping up

When attempting to install Angular in my terminal after completing the setup, I encountered the following error message: I have already installed: Node v6.10.3 npm ERR! Darwin 17.7.0 npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "-g ...

Getting around relative paths in an Angular application hosted by NGINX

I am using NGINX to host my Angular application. The frontend is accessible at http://localhost/, and the backend can be accessed at http://localhost/api/. While most of my configuration works correctly, I am encountering an issue with a relative path in a ...

Tips for utilizing an adaptive design with Angular

I am working on designing a page that allows for scrolling if needed. On each section of the page, I will be incorporating specific components with unique colors to enhance the layout. However, my current HTML code is not producing the desired result as sh ...

Using vue-class-component: A guide on creating and setting up reactive data

I am currently working with Vue.js using TypeScript and vue-class-component. My goal is to create a custom component with reactive data. Below is the code I have so far: <template> <div> <input v-model="data.name" placeholder=" ...

Exploring the art of styling in Angular6

I am looking to change the text color when a specific ID is clicked <nav class="navbar "> <ul class="navbar-nav"> <li *ngFor="let item of items"> <a class="nav-link" >{{item.title}}</a> ...

How can Angular JS handle multiple validators being triggered at once?

Hey there, I'm currently working with validators in my Angular form setup. Here's a snippet of how it looks - I utilize Validators.compose to combine custom validators. The errors from these validators are then displayed on the HTML component. My ...

Conceal the search bar for a specific route in Angular6

I am looking to show an input in my header only when the route is /home and hide it for all other routes. I have attempted some code but it does not seem to be working as expected. .html <div *ngIf="searchBarVisible"> <input class="form-cont ...

Dealing with NPM problems during Angular 9.0.7 setup issues

I encountered a problem after a recent Windows update that corrupted my system. I had to reinstall Windows, and now I am unable to run my Angular project, which was originally in version 9.0.7 with a package.json file. I tried installing Angular 9.0.7 glob ...