best method for implementing a TypeScript object

I've been searching high and low, but I can't seem to find the exact answer I need. Please inform me if my question has already been asked.

My goal is to construct an object in TypeScript that includes attributes of custom types.

The issue I'm facing is that my server supplies object data with URLs. I'm unsure how to handle this mapping situation. I hope I'm explaining it clearly enough – I'm still learning! By the way, I am working with Angular and TypeScript

Let me give you an example. This is what the object looks like:

export class Contact { 
    name : string;
    address : {
        street : string;
        city : string;
    }
}

However, the JSON retrieved from the server appears as follows:

{
    "name" : "firstname lastname",
    "address" : "http://localhost:5000/contacts/001"
}

If I use the address URL, I should receive the address in JSON format.

Thank you for your time!

Answer №1

Extract the JSON data fetched from the server and assign it to your variables as shown below:

...
.subscribe(
data => {
  this.firstName = data.first_name
  this.lastName = data.last_name
})

Please keep in mind that it is recommended to create a dedicated service for handling server requests.

Answer №2

If you're wondering how to convert data retrieved from a server into TypeScript objects, one approach is to create a static method within the class that can instantiate a new instance of the class. This method would take an object of type "any" as input and return an object with all properties mapped accordingly. You can then utilize this method after an HTTP request or subscription, depending on your specific setup.

export class Address {
   constructor(public name:string, description: string){
    }
   public static NewInstance(address: any){
      //perform mapping here
      return new Address(address.db_name, address.address);
   }
}
export class Student {
    constructor(
        public name : string,
        public classes: StudentClass[],
        public address: Address
    ){

    }
     public static NewInstance(student: any){
         let studentclasses = student.classes.map(n => StudentClass.NewInstance(n));
         return new Student(student.firstname+' ' + student.lastname, studentclasses, Address.NewInstance(student.addresss));
    }

}
export class StudentClass {
   constructor(public: name: string);
   public static NewInstance(studentclass: any){
        return new StudentClass(studentclass.namefromdb);
   }
}

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

Tips for using Angular's formatDate function to format dates

I am attempting to achieve a specific format using Angular's formatDate "2019-01-01T00:00:00Z" Here is the code I am using: formatDate( '2019-01-01', 'yyyy-MM-ddT00:00:00Z', 'en-US' ) The output I am getting is ...

Enhancing search capabilities in Angular 8.1.2 by filtering nested objects

I am in need of a filter logic similar to the one used in the example posted on this older post, but tailored for a more recent version of Angular. The filtering example provided in the older post seems to fit my requirements perfectly, especially with ne ...

What is the best way to determine a comprehensive map of every sub-store, their functions, and what data they contain?

Summary: Can all actions with their payloads be automatically grouped by sub-store in a composite store using a single type entity (e.g., interface)? I have implemented a Redux store with multiple sub-stores structured as follows: There is an action setA ...

Creating validation for an autosave reactive form in Angular 2: A step-by-step guide

Seeking advice on implementing an autosave feature for a reactive Angular 2 form. The idea is that as the user types in values, the form should automatically save if the input is valid. Below is the code snippet: export class BusinessFoundationsPage { ...

I'm looking to display the message between the specified start date and end date that is selected in the input field

Is it possible to utilize ngOnChange? <div> <label for="start">Start date:</label> <input type="time" name="starts" [(ngModel)]="starts"> <label for="end">End date: </label> <input type="time" name="end" [(ng ...

Scrolling horizontally in Ionic framework

In regards to the response found on Ionic - Horizontal scroll tab for Categories, I have a question. I am curious about what needs to be included in the category.model. Can anyone provide some guidance? ...

angular pipe and tap methods fail to execute the designated function

I am encountering a problem when calling a function in my login service. I have tried using a pipe and tap. Interestingly, when I use res => console.log(res), it outputs the desired result. However, when I attempt to call a function, it seems that the ...

Tips for altering Koa's HTTP status code for undeclared paths

If an undefined route is accessed on a Koa server, what is the best method to change the default HTTP status code and response body? Currently, Koa returns a 404 status and 'Not Found' text in the body. I intend to modify this to 501 (Not implem ...

Only filter the array by its value if the value is specified

Is there a way to apply this filter while only checking each condition if the value is not undefined? For instance, if taxId is undefined, I would like to skip it rather than using it as a filter criterion. this.subAgencies = demoSubAgencies.filter(fun ...

Tips for managing the output of an asynchronous function in TypeScript

The casesService function deals with handling an HTTP request and response to return a single object. However, due to its asynchronous nature, it currently returns an empty object (this.caseBook). My goal is for it to only return the object once it has b ...

Warning: Node encountering unexpected Unhandled Promise Rejection ERROR

I've encountered a problem in my code that is triggering an UnhandledPromiseRejectionWarning in Node, but I'm struggling to understand the root cause. Here's a simplified version of the code: export class Hello { async good(): Promise<s ...

Develop a new flow by generating string literals as types from existing types

I'm running into a situation where my code snippet works perfectly in TS, but encounters errors in flow. Is there a workaround to make it function correctly in flow as well? type field = 'me' | 'you' type fieldWithKeyword = `${fiel ...

What are some ways to specialize a generic class during its creation in TypeScript?

I have a unique class method called continue(). This method takes a callback and returns the same type of value as the given callback. Here's an example: function continue<T>(callback: () => T): T { // ... } Now, I'm creating a clas ...

What are the differences between TypeScript's 'Dictionary' type accessors for objects and objects with predefined members?

Currently, I am delving into TypeScript by following an online tutorial. While my programming background primarily consists of 'structurally' typed languages like C and ActionScript 3, TypeScript presents some new concepts for me to grasp. One p ...

Attempting to assign the object retrieved from the interface as the new value for window.location.href

I encountered an issue where the error message Type MyInterface' is not assignable to type 'string' popped up. Although I comprehend the problem, finding a suitable solution has proven to be challenging. MyInterface solely returns one item, ...

What causes an Angular Form to be validated before I even click the Submit button?

I have a Dynamic Angular Form. Upon loading the page, the form undergoes validation for errors. My goal is to implement a scroll-to-error directive that can automatically scroll and focus on the error div. However, I am facing an issue where the form is a ...

What is the process for creating a default button in Ionic framework?

Recently, I developed an app that includes a survey page. Each question in the survey has two buttons for the user to select: Yes or No. However, as a newcomer to using Ionic, I encountered an issue after building the code and checking the output. One of ...

pull information from mongodb into angular

I am attempting to retrieve data from MongoDB, but I keep seeing [object] [object]. How can I transfer array data from MongoDB to Angular? Here is the code snippet: import { Component, OnInit } from '@angular/core'; import {HttpClient} from &quo ...

Looking to display the ng-option in two lines within Angular 6?

How can I display data in a select dropdown with two lines for each option? I am currently using ng-select. <ng-select [(ngModel)]="selectedData" placeholder="Select Data"> <div *ngFor="let data of Data"> <ng-option [value]="da ...

Display an array depending on the value in Angular 2 when clicked

In my current Angular 2 project, I am dealing with a .json file structured like this: { "PropertyName": "Occupation", "DefaultPromptText": "occupation text", "ValuePromptText": { "WebDeveloper": "for web developer", "Administra ...