Using Angular to map an observable<t>

I'm currently working on a function that makes an API call and receives an array of objects as the response. My goal is to map this response to an observable of type Business, but I'm unsure about the correct mapping process within the getBusiness function.

Here is a sample response:

[
  {
    Id: 2,
    Name: "Joe"
  }
]
export interface Business {
    id: string;
    name: string;
}
getBusiness(): Observable<Business[]> {

        const url = "";

        return this.http.get(url, this.httpOptions)
        .pipe(
          map((data: Business[]) => data as Business[] )
        )
      }
@Component({
  selector: 'app-admin',
  templateUrl: './admin.component.html',
  styleUrls: ['./admin.component.scss'],
})
export class Component implements OnInit {

this.apiService.getBusiness() {
      .subscribe((res: Business[]) => console.log(res))
}

Answer №1

Implementing camelCase Conversion for API Response Objects

map((data: Business[]) => data.map(business => ({ id: business.Id, name: business.Name })) )

If you have control over the API, consider configuring it to return camelCase formatted properties to avoid extra processing. If not, a function can be created to convert property names to camelCase.

// Function to lowercase first letter
const firstLetterLower = val => val[0].toLowerCase() + val.substring(1);

// Function to convert object properties to camelCase
const camelcase = obj => Object.keys(obj).reduce((result, key) => {
  result[firstLetterLower(key)] = obj[key];
  return result;
}, {});

console.log(camelcase({
  Id: 2,
  Name: "Joe"
}));

Then you can utilize the function like this:

map((data: Business[]) => data.map(business => camelcase(business))

Answer №2

In my opinion, casting at the service is unnecessary.

Can you explain why const url = "";?

Service - Double-check the accuracy of the URL

getBusiness() {
    return this.http.get(url, this.httpOptions);
}

Component

ngOnInit() {
    this.apiService.getBusiness().subscribe(
     (res: Business[]) => console.log(res)
    );    
}

If there is a more efficient way to handle this task (even if it may be excessive)

Consider exploring NgRx/Store

Answer №3

When communicating with the httpclient, you can handle responses like this:

return this.http.get<Business[]>(url, this.httpOptions)

It's as simple as that. This approach simply provides type information to the compiler without altering the response itself. If you need to change the structure of the response by renaming properties, then manual mapping or other methods will be required.

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

To activate the ion-toggle, simply click on the ion-label

Currently, I am in the process of developing a page using Ionic 5. One of the features I am including is a 'remember me' button which utilizes <ion-toggle>. <ion-item> <ion-label>remember me</ion-label> <ion-to ...

Error: User authentication failed: username: `name` field is mandatory

While developing the backend of my app, I have integrated mongoose and Next.js. My current challenge is implementing a push function to add a new user to the database. As I am still relatively new to using mongoose, especially with typescript, I am followi ...

Attach [!hidden] to a dropdown menu choice using Angular 2

How can I implement a show/hide feature for a select box in Angular 2+? Here's what I have so far: <select> <option disabled selected>Flow progress</option> <option *ngFor='let flow of flows'>{{flow}}< ...

Leveraging a service within the constructor of an Angular model

My primary objective is to utilize a service within a model constructor that can access the necessary information and methods required by the constructor. To illustrate this concept, consider a hypothetical scenario I have concocted on the spot as an examp ...

Is there a way to customize the pagination layout of primeNG paginator in an Angular project

I've been struggling to customize the primeNG paginator in my Angular application. Specifically, I am trying to style the dropdown that lets users select the number of data entries. Despite my efforts to figure it out, I have not been successful in st ...

What are the solutions for resolving 'undefined' errors while working with TypeScript Interfaces?

When working with TypeScript in my Next.js project, I encountered the following error message: Type '{ banner: { id: number; bannerImageUrl: string; } | undefined; }' is not assignable to type 'IntrinsicAttributes & Banner'. Prope ...

Struggling to create an Extension Method for Map<TKey, TValue[]> in TypeScript

As a new Angular/TypeScript user, I am really enjoying using Extension methods. They work well on standard types, but now I am facing an issue while trying to write one for the Map data structure where values are arrays. Unfortunately, it does not seem to ...

I am facing difficulty in using Angular's ngIF directive with my object property for toggling visibility based on a condition

When writing a condition using *ngIf in my HTML code, I encountered an issue with displaying a mat-list-item based on an object property. Here is the code snippet: <mat-list-item *ngIf="object.conditionName" [ngClass]="((object.show) || i%2 != 0) ? ...

Angular is throwing an error message stating that it cannot find a differ that supports an object of type 'object'. NgFor only supports binding to iterables like Arrays

I am currently in the process of developing an Angular application that displays a list of projects and users from a PostgreSQL database. However, I have encountered difficulties when trying to display the list of users in HTML. The issue seems to be that ...

Exploring Angular: A Guide to Localisation and JSON

Looking at my JSON database structure below: { "users" : { "-Kowtg5yyK-DTIz91cQ8" : { "language" : "en", "uid" : "kNyDJnktxyakL6owhGd1rruGACb2", "userName" : "admin" } }, "localisation" : { "login" : { "en" : "Log ...

Having trouble entering more than one character in an input field for a nested FormArray within a Reactive Form

It seems like there may be a bug in the Reactive Form that I am working on. Any guidance from seasoned Angular Experts would be greatly appreciated. Symptom: Only able to input one character at a time in the designated input field. Issue: Occurs when the ...

What steps can I take to ensure the footer remains fixed at the bottom of the webpage?

I am facing a challenge with my footer component as it is currently being displayed at the end of another component. I want to ensure that it remains anchored at the bottom of the page regardless of the other components present. In addition to the footer ...

The parameter type 'Function' cannot be assigned to the parameter type 'ComponentType<never>'

Having an issue passing a component to the connect method from react-redux. The error message I'm receiving is as follows: Argument of type 'Function' is not assignable to parameter of type 'ComponentType'. Type 'Function&ap ...

Tips for implementing code in React to toggle the visibility of pages on click

Exploring React.js for the first time and struggling to toggle page visibility when clicking a button or outside the element. I prefer not to add any additional libraries to my project, so I am seeking alternative code solutions. Here's where I'm ...

Adapt button functionality according to selected dropdown value in Angular

I have implemented a License Key generation process in my application where user input is used to create a unique key that is then passed to the Java backend. The code snippet for generating the key is as follows: @PostMapping("/generate") public Li ...

Issue with Angular 7: "Unspecified name attribute causing control not found"

As I delve into the creation of my initial Angular application, I find myself faced with a series of errors appearing in the development mode console: ERROR Error: "Cannot find control with unspecified name attribute" ERROR Error: "Cannot f ...

Guide on how to determine a true or false outcome post an HTTP request within an angularJS function

Environment AngularJS 4 I am currently trying to execute an HTTP Request within a function, but I am having trouble sending the result back. Below is my code with some comments. I am expecting either a true or false value, but unfortunately, I am receivin ...

Is it secure to transmit Tenant ID's as GET parameters to the API in a Multi-Tenant database environment?

When working with a Multi-Tenant database, is it secure to pass Tenant ID's as query string parameters to the API while using popular JavaScript-based UI platforms like Angular or Vue and ensuring both the site and the API are HTTPS? For example, let ...

Unleash the power of a module by exposing it to the global Window object using the dynamic

In my development process, I am utilizing webpack to bundle and manage my TypeScript modules. However, I am facing a challenge where I need certain modules or chunks to be accessible externally. Can anyone guide me on how to achieve this? Additional conte ...

Encountering a compilation error when implementing ActionReducerMap in combination with StoreModule.forFeature

In my Angular project, the structure is organized as follows: /(root or repo folder) |_ projects |_ mylib (main library to be exported from the repo) |_ sample-app (created for testing 'mylib' project in other projects) To manage appli ...