Transforming the Server-side model to the Client-side model within Angular 4

My Server-side C# model

 public  class Instructor:Entity
 {
    public string Name { get; set; }
    public string PhoneNo { get; set; }
 }

Client-side TypeScript model

export class Instructor extends Entity {
    public name:string;
    public address:string;
    public phoneNo :string;
}

Client-side service

getDataById(id: string):Observable<T> {
    return this.repo.get(this.subUrl+'query',id).map( (res)=>{ return <T> res.json()})
}

Client-side controller

this.subscription= this.instructorService.getDataById(this.id).subscribe( (data:Instructor) =>{
       console.log(data);
       this.model.name=data.name;
       console.log(this.model))};

Output result: Result displayed in browser

Is there a more efficient way to perform this mapping?

this.model.name=data['Name'];

I prefer using this approach for the mapping or any other better suggestions

this.model.name=data.name;

Your assistance is greatly appreciated

Answer №1

Make sure to declare your teacher with a lower-case name. When you receive an object with an upper-case Name, TypeScript may complain that the data parameter does not have a Name member. In this case, consider declaring your data parameter as any instead of Teacher.

this.subscription= this.techerService.getDataById(this.id).subscribe((data:any) =>{
       console.log(data);
       this.model.name=data.Name;
       console.log(this.model);

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

In Angular 2, I am having trouble reaching the properties of an object nested inside another object

I have a variable named contact. When I used console.log(contact) to display its contents, this is what I got: addresss:[] company:"" emails:[] id:3 internet_calls:[] lat:"10.115730000000001" lng:"76.461445" name:"Diji " phones:[] special_days:[] timesta ...

What is the correct way to effectively share data between components using a service?

I've been diving into learning Angular 2 and successfully implemented data sharing between sibling components using input/output functions. Check out my working example here. // Our root app component import {Component, NgModule} from '@angular ...

There was an error encountered during the npm install process

C:\Users\Mayur Saner\pmrm>npm install npm ERR! code ENOTFOUND npm ERR! errno ENOTFOUND npm ERR! network request to http://registry.npmjs.org/@fortawesome%2ffontawesome-free failed, reason: getaddrinfo ENOTFOUND proxy.company.com npm ERR! ...

Why are the class variables in my Angular service not being stored properly in the injected class?

When I console.log ("My ID is:") in the constructor, it prints out the correct ID generated by the server. However, in getServerNotificationToken() function, this.userID is returned as 'undefined' to the server and also prints as such. I am puzz ...

Switching between two distinct templateUrls within an Angular 6 component

When working with Angular 6, we are faced with having two different templates (.html) for each component, and the need to change them based on the deployment environment. We are currently exploring the best practices for accomplishing this task. Some pos ...

What purpose does a cast serve when used on a return type that is defined generically?

Consider this straightforward property access function export function accessProperty<T, K extends keyof T, P extends T[K]>(name: K, v: T): P { return v[name] as P } What is the significance of the cast as P in this context? I experimented with ...

Using setAttribute will convert the attribute name to lowercase

When creating elements, I use the following code: var l = document.createElement("label");. I then assign attributes with l.setAttribute("formControlName","e");. However, a problem arises where the setAttribute method converts formControlName to lowercase ...

Fixing a compare function problem in Angular 6 mat-select

Being currently engrossed in an angular 6 project, I find myself grappling with a mat-select element that necessitates the use of the compareWith function due to my selection of objects. Curiously enough, even when I refrain from selecting any option, it ...

What is a more efficient method for incorporating optional values into an object?

Currently, I am utilizing the optional addition feature in this way: ...(!!providerId && { providerId }), ...(!!practiceId && { practiceId }), Is there a more elegant shorthand method to replace this logic, such as: yield createRemark ...

Pictures are not visible on mobile devices

Currently, I am utilizing Ionic 2 for my project. While the images are displaying correctly on the browser, they are not showing up on the device. This issue has been perplexing me. I attempted to resolve this problem by using the following code: <i ...

Is it possible to use conditional logic on child elements in formkit?

I am a bit confused about how this process functions. Currently, I am utilizing schema to create an address auto complete configuration. My goal is to have the option to display or hide the fields for manual input. This is the current appearance of the ...

Saving in prettier differs from running it with npm

./file.ts (INCORRECT) import { jwtGroupClaimToRolesDomain, ScopeIds } from '@invison/shared'; import { Injectable, NestMiddleware } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { Response } fro ...

Steer clear from using the implicit 'any' type while utilizing Object.keys in Typescript

I have a unique situation where I need to loop over an Object while maintaining their type without encountering the error "Element implicitly has an 'any' type because 'ContactList' has no index signature". Despite extensive discussion ...

Restrict the frequency of requests per minute using Supertest

We are utilizing supertest with Typescript to conduct API testing. For certain endpoints such as user registration and password modification, an email address is required for confirmation (containing user confirm token or reset password token). To facilit ...

What steps should I follow to ensure that TypeScript is aware of the specific proptypes I am implementing?

Is there a way to instruct TypeScript on the prop types that a component is receiving? For example, if multiple is set to true, I would like TypeScript to expect that selectValue will be an array of strings. If it's not present, then TypeScript should ...

Receiving an error stating "module not found" when attempting to retrieve the NextAuth session using EmailProvider in getServerSideProps

Trying to access the NextAuth session from a server-side call within getServerSideProps, using an EmailProvider with NextAuth. Referring to an example in NextAuth's documentation, I'm attempting to retrieve the session from getServerSideProps. T ...

Create an animated hamburger menu using Tailwind CSS and Angular framework

Within my Angular project, I have successfully integrated Tailwind UI to handle the opening and closing of the hamburger menu by utilizing the code below: <header> <div class="-mr-2 -my-2 md:hidden"> <button type="button ...

Retrieve all items that match the ids in the array from the database

I'm having trouble receiving a list of items that match with my array of ids. Here's a snippet from the Angular component code: this.orderService.getSpecyficOrders(ids) .subscribe(orders => { ... Where ids is an array of [{_id : ID }, ...

Monitor the true/false status of each element within an array and update their styles accordingly when they are considered active

Currently, I am attempting to modify the active style of an element within an array. As illustrated in the image below - once a day is selected, the styles are adjusted to include a border around it. https://i.stack.imgur.com/WpxuZ.png However, my challe ...

What is the best way to transform a Storybook typescript meta declaration into MDX format?

My typescript story file is working fine for a component, but new business requirements call for additional README style documentation. To meet this need, I am trying to convert the .ts story into an .mdx story. However, I am facing challenges in adding de ...