Guide to transforming API Response into Custom type in Angular 5

Describing my method to structure the API Response -

 interface MyTest {
 property2: string
 }

Incorporating Angular 5 Service Code -

getAPI(searchKey: string) {
this.productsAPIUrl = 
                  https://localhost:44331/api/SampleData/WeatherForecasts2";

return this.http.get<MyTest>(this.productsAPIUrl);
}

The Result from my API - https://localhost:44331/api/SampleData/WeatherForecasts2 is

{"property1":"Property1","property2":"Property2","property3":"Property3"}

Utilizing the Angular Service in my Component as follows -

public incrementCounter() {

this.getAutocompleteSuggestions().subscribe((data: MyTest) => {
  console.log(data);
});
}

The Query arises after calling the Angular Service, receiving the complete Response. Although I have specified 'MyTest' type with only property2, why do complete results get returned?

What steps are needed to segregate the API Response and how can it be aligned to custom model type MyTest????

Requirement limited to Property2 data. How to effectively map it???

Answer №1

When TypeScript is compiled into JavaScript, the types defined in TypeScript do not hold any significance during runtime.

To work around this, you can map the object received into a new object as demonstrated in this example:

import { from } from 'rxjs';
import { map } from 'rxjs/operators';

interface MyTest {
  property2: string
}

class Example {
  private getAutocompleteSuggestions() {
    return from([{"property1":"Property1","property2":"Property2","property3":"Property3"}]);
  }

  public incrementCounter() {
    this.getAutocompleteSuggestions().pipe(map(data => { return { property2: data.property2}})).subscribe((data: MyTest) => {
      console.log(data);
    });
  }
}

new Example().incrementCounter();

Answer №2

When dealing with TypeScript, it's important to remember that there is no concept of runtime casting. Type hinting in TypeScript simply informs the compiler how to handle a given object. For example, when you have:

this.getAutocompleteSuggestions().subscribe((data: MyTest)

you are essentially telling the compiler to "interpret the subscription argument as if it were of type MyTest," even though the actual object will never be exactly of that type (just a plain object).

If you require the entity to match the exact type, you will need to manually transform it yourself using a method like pipe map.

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

Guide on integrating an element into a different element in a Vue 3 Tree Viewer

In my current setup, I've implemented a TreeView component that holds a tree. Each tree entry includes Children with their own unique label, perm, and further children. Take a look at an example of the tree: App.vue let tree = ref({ label: 'o ...

Passing a custom data type from a parent component to a child component in React

I'm currently working on developing a unique abstract table component that utilizes the MatTable component. This abstract table will serve as a child element, and my goal is to pass a custom interface (which functions like a type) from the parent to t ...

How can you define the types of function arguments when destructuring arguments in TypeScript?

TS throws an error that states: Error:(8, 20) TS7031: Binding element 'on' implicitly has an 'any' type. Error:(8, 24) TS7031: Binding element 'children' implicitly has an 'any' type. Below is the function I am wor ...

Is there a way to determine if a tuple is of infinite or finite length?

Is there a way to determine if a tuple is finite or infinite? I've been working on a solution, but it doesn't cover all cases: type IsFinite<T extends any[], Finite = true, Infinite = false> = T extends [] ? Finite : T extends (infer E ...

Jhipster Jenkins is throwing an error related to different modules, causing Webpack to have trouble distinguishing the context and failing to load

I need assistance with setting up a Jhipster project in Jenkins. Everything works fine locally, but when running 'yarn nun webpack:build' in Jenkins, I encounter the following error: ERROR in NaNbut they point to different modules "(<jenk ...

Having trouble obtaining React 15.6.1 type definitions: "ERROR: Repository not found."

Trying to set up the type definitions for React 15.6.1, but encountering an error: $ npm install --save @types/react npm ERR! git clone <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="88efe1fcc8efe1fce0fdeaa6ebe7e5">[email&# ...

Deploying Angular to a shared drive can be done in a

My angular.json file contains the following line: "outputPath": "Y:\Sites\MySite", After running ng build, I encountered the error message: An unhandled exception occurred: ENOENT: no such file or directory, mkdir 'D:& ...

Using RXJS with Typescript to wait for an observable to emit until another observable of type boolean evaluates to false

In my current setup, when a user navigates in a view, an API call is made to fetch the data for that specific view. This data is then used later on to decide whether a dialog should pop up when a user performs an action. While the solution is functional a ...

When trying to style a Material UI component in Mui v5, no matches for overloads were found

In my attempt to enhance the style of a Material UI Component (TextField) shown in the image, I encountered an error that seems to persist no matter what troubleshooting steps I take. Interestingly enough, I never faced such issues when working with styled ...

The issue of ngModel not binding to the value of ion-select in Angular Ionic

Having an ion select outside of a form with an ngModel attribute bound to "selectedValue", I encounter an issue where my selections are not being properly populated in the selectedValue variable even though they appear in the ionChange method. The main pur ...

Model driven forms in Angular 4 do not display validation errors as expected

I'm having trouble getting validation errors to display with the code below. Can anyone provide some assistance? I've set the validators in my component using Form builder. The validation works when I use a single form-group, but it's not w ...

Guide on moving elements to a different list with the help of the Angular DragDrop CDK Service

I encountered a unique situation while working on my project where I needed to implement a drag and drop feature for multiple lists using Angular CDK's DragDrop service. While I was able to successfully move items within a single list, transferring an ...

Experiencing Issues with Angular Service Worker - Outdated Build Persisting - Seeking Angular Resolution

A Revision to an Edit: The answer below clarifies the issue. Despite Angular SW working properly with hashing, there was a problem with the server re-hashing certain bundles, causing a mismatch between the client and server SW versions. Edit: Allow me t ...

The issue I encountered with Angular's Mat-Select component is that the openedChange

When a user opens the mat-select, I am attempting to set CSS style using custom code. However, I am encountering an undefined error. Upon checking in the console, I noticed that the panel value is returning undefined. Can someone please advise me on how to ...

The reason for my inability to include a fresh method in String.prototype using typescript

I attempted to extend the String.prototype with a new method, but I encountered an issue. interface String { newMethod(): void } String.prototype.newMethod = function() {} Although there were no errors in the typescriptlang.org playground, I received ...

Setting up gulp-typescript for Angular 2: A comprehensive guide

Right now I am utilizing the tsc compiler with the watch flag in the command prompt. It functions correctly, loading all definition files and successfully compiling each angular2 file. However, it is quite cumbersome to use via the shell window. My object ...

Choose the AuthGuard category in real-time

My application intends to employ two distinct authentication strategies - one for users accessing via a browser and another for the public API. A specific header will be set for browser users, allowing my app to determine the appropriate auth strategy base ...

How can I access the value of one method within the same class and use it in another method in Ionic?

I encountered an error while trying to utilize data from my API call in IONIC's home.ts file for the google map method also located in home.ts. Unfortunately, this resulted in a null or undefined error. Is there a way to effectively use data from one ...

The inRequestScope feature seems to be malfunctioning and is not functioning as intended

Need help with using inRequestScope in inversifyJS For example: container.bind<ITransactionManager>(Types.MysqlTransactionManager).to(MysqlTransactionManager).inRequestScope() ... container.get<ITransactionManager>(Types.MysqlTransactionMana ...

Strategies for Implementing Pagination in an Angular 2 HTML Table Without the Use of Third-Party Tools

I have an HTML table that displays basic details along with images. I am looking to implement pagination for this table in Angular 2. Are there any alternatives to using ng2-pagination? ...