Transform the response from HttpClient into an array containing objects

In my Angular 7 project, I initially had the following code for the Envelope class:

export class Envelope<T> {
  result: T[];

  constructor(result: T[]) {
    this.result = result;
  }
}

Then, I mapped

Observable<Envelope<Todo>>
returned by todoService to Observable<TodoModel[]>:

let models: Observable<TodoModel[]> = this.todoService.get()
  .pipe(
    map((envelope: Envelope<Todo>) => 
      envelope.result.map((todo: Todo) => { 
        return {
          content: todo.content
          // Other properties
        };
      })));

However, the structure of Envelope has now changed to result: T instead of result: T[]:

export class Envelope<T> {
  result: T;

  constructor(result: T) {
    this.result = result;
  }
}

Now, I need to map

Observable<Envelope<Todo[]>>
to the same Observable<TodoModel[]>:

let models: Observable<TodoModel[]> = this.todoService.get()
  .pipe(
    map((envelope: Envelope<Todo[]>) => 
      envelope.result.map((todo: Todo) => { 
        return {
          content: todo.content
          // Other properties
        };
      })));

I have tried various options but am encountering the following error:

Argument of type 'OperatorFunction<Envelope<Todo[]>, { content: string; }[]>' 
is not assignable to parameter of type 'OperatorFunction<Envelope<Todo>, { content: string; }[]>'.

Type 'Envelope<Todo[]>' is not assignable to type 'Envelope<Todo>'.
Type 'Todo[]' is missing the following properties from type 'Response': content.

If anyone could provide guidance on how to successfully do the mapping, it would be greatly appreciated.

Update

The API response looks like this:

{
  "result": [
    { "id": 1, "title": "T1", content: "C1" },
    { "id": 2, "title": "T2", content: "C2" }
  ]
} 

And the TodoService returns it as an

Observable<Envelope<Todo[]>>
where Todo is defined as:

interface Todo {
  id: number;
  title: string;
  content: string;
}

In the component, I need to map

Observable<Envelope<Todo[]>>
to Observable<TodoModel[]> where TodoModel is defined as:

interface TodoModel {
  title: string;
  content: string;
}

While my application has more complex scenarios, this is the basic structure I am working with.

Answer №1

Are you looking to inspect the envelope? Perhaps a clearer approach would be beneficial. If the envelope holds a collection of tasks

data: Observable<TaskModel>; 

    this.taskService.fetch()
          .subscribe((envelope: any) => {
            this.data = envelope.taskList.items;       
          });

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

Issue with typings in TypeScript is not being resolved

I have integrated this library into my code Library Link I have added typings for it in my project as follows Typings Link I have included it in my .ts file like this import accounting from "accounting"; I can locate the typings under /node_modules ...

Declare the push method within the Countly.q array in a TypeScript declaration file

Is there a way to declare Countly push add_event method in the following manner? Countly.q.push(['add_event',{ "key":"action_open_web", }]); I attempted to do this inside a declaration file (.d.ts) but it did not work. Here ...

Tips for importing font files from the node_module directory (specifically otf files)

We cannot seem to retrieve the fonts file from the node module and are encountering this error message. Can't find 'assets/fonts/roman.woff2' in 'C:\Projects\GIT2\newbusinessapp\projects\newbusinessapp\src ...

What is the best way to showcase the chosen information?

Typically, I maintain a list of specific entries within cards. When clicking on one of the records in the card, the corresponding data table is supposed to be displayed below that record. An issue arises where after selecting a record and displaying its d ...

Is Angular 5 capable of providing polyfill support for async/await in IE11?

Our software development team has created a program that requires support from IE11. Despite various sources indicating that IE11 does not support async/await, our simple Angular 5 project using async/await functions perfectly in IE11. This raises the ques ...

What steps can I take to persistently subscribe to SignalR from an Angular service even in the event of connection failures?

Is there a way to safely attempt to connect to SignalR with intervals between attempts until the connection is established? Also, does anyone have advice on how to handle the different stages of connectivity to the web sockets effectively? We are utilizin ...

React is unable to identify the property that was passed to a styled-component in Material UI

Custom Styled Component Using Material-UI: import { Typography } from '@material-ui/core'; const CustomText = styled(Typography)<TextProps>` margin-bottom: 10px; color: ${({ textColor }) => textColor ?? textColor}; font-size: ${( ...

Utilizing Angular to lazily load multiple routes/paths within a single module

I am currently in the process of setting up multiple horizontal routes (not nested) and grouping them into one lazy-loaded module. However, I am facing a challenge trying to properly match these routes within the lazy-loaded feature module itself. Below ...

What is the most efficient way to modify a list within another list variable in Angular without impacting the parent list?

Here is a data list that I am working with: subscriberDataList -> wipEligibilityList -> dependentList dependentList -> wipEligibilityList -> eligibilityList wipEligibilityList[0] -> status - ...

Can the details of a package be retrieved from a Nuget private store using a REST API?

Currently working on an Angular 8 project that involves displaying the details of Nuget packages from a custom store. I am wondering if it is possible to retrieve package details from an NPM custom store using a REST API? Something similar to: https://lea ...

Ways to sequentially execute API calls rather than concurrently

Update: Find the complete solution at the end of this answer. Consider the following code snippet: @Injectable() export class FileUploader { constructor(private http: Http) {} upload(url: string, file: File) { let fileReader: FileReader ...

Utilizing Angular 2's Routerlink with *ngIf and Parameters

Currently, I am facing an issue with a routerlink that includes a parameter: http://localhost:4200/item/1 I am trying to figure out how to implement an *ngIf statement with a parameter.... Here is what I have attempted so far: <div *ngIf="router.url ...

Angular 7's Singleton Service Feature

My service setup looks like this: export abstract class ILoggingService { // abstract functions here } export class LoggingService implements ILoggingService { // service implementation } export class MockLoggingService implements ILoggingServic ...

Assigning union values to an object array: a guide for Typescript

When working with union typed values in an object array, how should the setState() function be implemented? enum SomeStateEnum { IsRunning, Name, } type PersonState = { [SomeStateEnum.IsRunning]: boolean; [SomeStateEnum.Name]: string; }; const st ...

What is the best approach to prevent the occurrence of two instances of | async in this particular scenario (version 4.0

Is there a way to achieve the desired outcome in this component without using .subscribe()? I attempted to implement *ngIf="user$ | async as user" but encountered difficulties with it. What is the best approach to create a local variable using user$ | asy ...

The essential guide to creating a top-notch design system with Material UI

Our company is currently focusing on developing our design system as a package that can be easily installed in multiple projects. While the process of building the package is successful, we are facing an issue once it is installed and something is imported ...

Ways to universally establish values of a mapped type

Take a look at the code snippet below: type Properties = { item0: { item0: string }; item1: { item1: string }; item2: { item2: string }; item3: { item3: string }; item4: { item4: string }; }; type Func<N extends keyof Properties> = ({}: Pr ...

Ways to extract X-Total-Count from json-server using Angular's http.get function

Currently, I am utilizing json-server on localhost:3000. The setup is running smoothly, and I can fetch data in Angular through http.get. My objective is to access the response header X-Total-Count within the Angular .subscribe method. However, I am unab ...

Utilizing TypeScript with Vue3 to Pass a Pinia Store as a Prop

My current stack includes Typescript, Pinia, and Vue3. I have a MenuButton component that I want to be able to pass a Pinia store for managing the menu open state and related actions. There are multiple menus in the application, each using the same store f ...

Enhance your FullCalendar experience with React by displaying extra information on your calendar

I am new to using React and FullCalendar, and I have a page layout similar to the image linked below. https://i.sstatic.net/MooTR.png Additionally, I have a list of events structured as shown: id: "9", eventId: "1", ...