Mapping response data to a new type using TypeScript in Angular 2

Consider the following:

userGroups: IUserGroup[];
this.service.getUserGroups().subscribe(g => this.userGroups = g);

The getUserGroups function returns IUserDifferentGroup[]. However, both IUserGroup and IUserDifferentGroup share the same fields, with IUserGroup having some additional ones. How can we map the response to a new type?

interface IUserDifferentGroup{
    Name: string;
    Code: string;
    Id: number;
}

interface IUserGroup {
    Id: number;
    GroupName: string;
    Visible: boolean;
    IsDefault: boolean;
    CanAssociated: boolean;
}

Answer №1

Insert this code snippet within the subscribe function:

this.service.getUserGroups().subscribe(g => this.userGroups = g as IUserGroup[]);

MODIFICATION

Based on feedback, update the code as follows:

interface IUserDifferentGroup {
    Name: string;
    Code?: string; // <-- changed to optional
    Id: number;
}

interface IUserGroup {
    Id: number;
    GroupName: string;
    Visible: boolean;
    IsDefault: boolean;
    CanAssociated: boolean;
}

Then, revise the subscribe method to:

this.service.getUserGroups().map(g => return {Name: g.GroupName, Id: g.Id})
 .subscribe(g => {
  this.userGroups = g as IUserGroup[];
});

Try implementing these changes and verify if it resolves the issue.

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

Error: You're attempting to read content that has already been accessed

Encountered the following error message: sp-webpart-workbench-assembly_en-us_b854c4b93cc10a271230fd4a9e7b2b9b.js:661 Uncaught (in promise) TypeError: Already read at t.e.json (sp-webpart-workbench-assembly_en-us_b854c4b93cc10a271230fd4a9e7b2b9b. ...

Using a for loop in Javascript with a specified increment value

I am working with an array containing 100 elements. My goal is to extract elements from the 10th to the 15th position (10, 11, 12, 13, 14, 15), then from the 20th to the 25th, followed by the 30th to the 35th, and so on in increments of 4, storing them in ...

Methods for organizing consecutive elements within an array in Javascript/Typescript

Let's explore this collection of objects: [ { key1: "AAA", key2: "BBB" }, { key1: "BBB", key2: "CCC" }, { key1: "CCC", key2: "DD ...

When using create-react-app with JEST to run tests, TypeScript errors are not displayed

When I write incorrect TypeScript code in my project set up with create-react-app, running tests using npm test does not show any errors in the terminal. Is this normal behavior? It would be helpful to see these errors to avoid writing incorrect TypeScript ...

A guide to creating test cases for conditional statements in Angular using Jasmine

I am currently working on creating test cases for a custom directive in Angular. I have shared my code on StackBlitz. I would appreciate any guidance on how to address the highlighted if else statements below: if (trimmedValue.length > 14) { // Loo ...

Unlock the power of Angular Component methods even when outside the Angular library with the help of @ViewChild()

In my Angular library, there is a component called AComponent which has its own template, methods, and properties. Once the Angular library is packaged, it becomes available as a NuGet package for other projects to utilize. @Component({ selector: ' ...

Error in pagination when using MAX() function in PostgreSQL query

Here is the query I am using to retrieve the latest message from each room: SELECT MAX ( "Messages"."id" ) AS messageId, "Rooms"."id" FROM "RoomUsers" INNER JOIN "Rooms" ON " ...

The Angular Fire Firestore module does not include the 'FirestoreSettingsToken' in its list of exported members

When I initially compiled my project, this issue occurred. The error message displayed is as follows: Module '".../node_modules/@angular/fire/firestore/angular-fire-firestore"' has no exported member 'FirestoreSettingsToken' In my a ...

Is ngForIn a valid directive in Angular 4?

While attempting to loop over the properties of an object using *ngFor with in, I encountered a challenge. Here is a sample code snippet: @Controller({ selector: 'sample-controller', template: ` <ul> <li *ngFor="let i in o ...

Using JSDoc to Include TypeScript Definitions

I've been attempting to utilize the ts-xor package, which provides a TypeScript definition: export declare type XOR<T, U> = (T | U) extends object ? (Without<T, U> & U) | (Without<U, T> & T) : T | U; This is how I'm imp ...

The Tools of the Trade: TypeScript Tooling

Trying out the amazing Breeze Typescript Entity Generator tool but encountering an error consistently. Error: Experiencing difficulty in locating the default implementation of the 'modelLibrary' interface. Options include 'ko', 'b ...

The data retrieved from Firebase is coming back as not defined

I am currently working on an Angular component that is designed to showcase data retrieved from Firebase in a table using a service: <table class="table table-sm"> <thead> <th>Animal Name</th> <th>Species</th> ...

conceal a div in Angular when the user is authenticated

One of my tasks involves managing the visibility of a div based on whether the user is logged in. This functionality is achieved by utilizing an authentication service in Angular and tokens from Django. Component.html <a *ngIf="authService.isLoggedIn( ...

Is it better to wait for an ajax request to finish loading in a vue or angular SSR environment?

Currently, I have a Vue or Angular application in place. Upon loading the app component, an AJAX request is made to retrieve the data that will be displayed in the child components. In addition, I am utilizing server-side rendering (SSR). My query pertai ...

Is there a way to bypass type assertion while implementing spread syntax in an array that includes generics?

export type NavIconsName = | 'home-filled' | 'home-regular' | 'folder-filled' | 'folder-regular'; export interface INavLinkBase<T = {}> { linkName: string; svgIcon?: ISvgIconProps<T>; selec ...

Exploring Angular 5: Injecting a Service in Unconventional Places

I am attempting to utilize a service outside of a component. My main objective is to use my service within a function wrapped in a data object that I would then pass to my router for use by my Breadcrumb later on. Here is an example of what I envision: ...

`Why Lazy Loading Modules in Angular2(RC-6) is Not Possible`

In my Angular2 application, I am working on implementing lazy loading for feature modules. The application consists of a root module and two feature modules. The paths for the root module and its routing files are: app/public/scripts/app.module.ts app/pu ...

Acquiring the download link for Firebase Storage in Angular 2+ technology

reference: AngularFireStorageReference; task: AngularFireUploadTask; uploadState: Observable<string>; uploadProgress: Observable<number>; downloadLink: Observable<string>; beginUpload(event) { const id = Math.floor(Math.random() * 1000 ...

The Angular Button fails to display when all input conditions are met

I'm currently working on validating a form using this link. The requirement is simple - when an input field is invalid, the `save` button should be disabled. Conversely, when all input fields are valid, the `SAVE` button should be enabled/shown. The & ...

What are some ways to enhance Rxjs syntax?

save(): void { combineLatest(this.selectedSorting$, this.selectedFilters$) .pipe( map((data) => { let obj = {}; if (data[0]) { obj['fil ...