Assigning values to an object in Angular: A step-by-step guide

I have a RestApi that sends me the response in Json Format with an address object containing fields such as address1, address2, city, etc. To handle this, I defined an interface within my application to outline these objects:

export interface ISurveyResponseDetail {
  docID?: string;
  permission?: string;
  property?: IProperty;
  surveyID?: string;
}
export interface IProperty {
  address1?: string;
  address2?: string;
  city?: string;
  state?: string;
  zip?: string;

In my TypeScript file, I am looking to utilize a data adapter to map the response into this interface. However, I am unsure of how to properly assign and use the property Object of type IProperty with the values:

static adaptSurveyResponseDetail(data): ISurveyResponseDetail {
        if (data) {
            return {
                property:
                // address1 _.get(data, 'property.address1', null),
                // city _.get(data, 'property.city', null),
                docID: _.get(data, 'docID', null),
                permission: _.get(data, 'permission', null),
                surveyID: _.get(data, 'survey_id', null),
              };
            } else {
            return data;
        }

    }

Answer №1

Consider implementing a function like this:

function parseSurveyResponse(data): SurveyData {
    if (data) {
      return {
        location: {
          street: data.street,
          apt: data.apt,
          city: data.city,
          state: data.state,
          zipCode: data.zipCode,
        },
        documentID: data.documentID,
        access: data.access,
        surveyNumber: data['survey_number'],
      };
    } else {
      return data;
    }
  }

Answer №2

My RestApi sends responses in a Json Format.

Perhaps you're overcomplicating things? The HttpClient has user-friendly methods that allow for easy casting of parsed json responses to an interface.

fetchSurveyData() : Observable<ISurveyData> {
  return httpClient.get<ISurveyData>('/api/survey/data');
}

Answer №3

It is recommended not to make all properties of your interface optional. Instead, consider defining an additional type as partial and utilize it in situations where flexibility is necessary.

export interface ISurveyResponseDetail {
  property: IProperty;
  docID: string;
  permission: string;
  property: IProperty;
  surveyID: string;
}

export type ISurveyResponseDetailPartial = Partial<ISurveyResponseDetail>;

export interface IProperty {
  address1: string;
  address2: string;
  city: string;
  state: string;
  zip: string;
}

export type IPropertyPartial = Partial<IProperty >;

Avoid using underscore to assign default values as null. It is better to define a default object instead.

const DEFAULT_SURVEY_RESPONSE_DETAIL: ISurveyResponseDetail = {
  property: DEFAULT_PROPERTY,
  docID: null,
  permission: null,
  property: null,
  surveyID: null
}

const DEFAULT_PROPERTY: IProperty{
  address1: null,
  address2: null,
  city: null,
  state: null,
  zip: null
}

An adapter is not required to reconstruct the object, as the HTTP client can handle deserializing JSON into a type automatically. If you wish for missing properties to be set as null, create a new object using the default object as a base and then apply the specified values. Any absent properties will remain as null.

getSurveyResponseDetail() : Observable<ISurveyResponseDetail> {
  return this.http.get<ISurveyResponseDetail>(...).pipe(
     map(data => {
        const property = {...DEFAULT_PROPERTY, ...(data.property || {})};
        return {...DEFAULT_SURVEY_RESPONSE_DETAIL, ...data, property};
     });
}

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

Creating nested routes with parameters in NestJS is a powerful feature that allows for dynamic routing

I have a requirement to create an API with routes that share a common URL part along with a parameter. For my particular case, the routes should follow this structure: /accounts/:account/resource1/:someParam /accounts/:account/resource2/:someParam/whate ...

Error: JSON parse error - unexpected character 'a' at index 1

I'm encountering an issue while attempting to change the album title from "cars" to "car". The error message I keep receiving is: SyntaxError: Unexpected token a in JSON at position 1. Any ideas on what might be causing this problem? Below is the cu ...

The term 'EmployeeContext' is being utilized as a namespace in this scenario, although it actually pertains to a type.ts(2702)

<EmployeeContext.Provider> value={addEmployee, DefaultData, sortedEmployees, deleteEmployee, updateEmployee} {props.children}; </EmployeeContext.Provider> I am currently facing an issue mentioned in the title. Could anyone lend a hand? ...

Fashion for the repetitive elements, activated by events

Looking for ways to style a specific table element that is generated from a repeat.for loop on a <td> tag. <td repeat.for="field of fields" class="${field.fieldKey == 'validTo' ? 'fontweigth: bold;': ''}"> b ...

Leverage external libraries in Angular

I discovered a library that I want to incorporate into my app: https://www.npmjs.com/package/jquery-animated-headlines However, I am struggling with the process of importing it. Firstly, I have added these lines in my angular-cli.json: "styles": [ . ...

insert information into a fixed-size array using JavaScript

I am attempting to use array.push within a for loop in my TypeScript code: var rows = [ { id: '1', category: 'Snow', value: 'Jon', cheapSource: '35', cheapPrice: '35', amazonSource ...

Access a calendar for selecting a date within a v-select component in VUE

Currently, I am facing an issue with a v-select feature on my website. It contains four items for selecting different dates, with the last item designated for choosing a manual date. My intention is to have a menu or dialog box pop open when this option is ...

Issue arises when integrating Angular 13 with ngrx and OAuth2: encountering difficulties in creating an effect

Currently, I'm following an example that uses an earlier version of Angular and ngrx. You can find the tutorial on NGRX Authentication in Angular with asp.net core here. This is what my Auth.action.ts file looks like: import { createAction, props } f ...

Find out if a dynamically imported component has finished loading in Nextjs

Here is a simplified version of my current situation import React, { useState } from 'react'; import dynamic from 'next/dynamic'; const DynamicImportedComponent = dynamic(() => import('Foo/baz'), { ssr: false, loading ...

Using TypeScript, you can access the constructor of a derived type by calling it with the

In my TypeScript project, I am attempting to generate or duplicate a child object using a method within the base class. Here is my simplified code setup: abstract class BaseClass<TCompositionProps> { protected props: TCompositionProps; prot ...

What is the best method for displaying an HTML string within an HTML file in Angular 5?

I have declared an array in my TypeScript file like this: import {Component, OnInit} from '@angular/core'; import { DomSanitizer } from '@angular/platform-browser'; @Component({ selector: 'app-foo', template: ...

Error: Unable to locate module with associated type definitions when utilizing Typescript in Next.js

Currently, I am working on a next.js project that I'm attempting to integrate typescript into. The structure of my folders is organized as follows: api aggregation.ts interfaces index.ts components Component1 index.js index.module.css ...

How can we prevent the Race operator in RxJS from canceling the "losing" HTTP Request Observable?

I am currently working on creating a race condition using RxJS for querying 2 APIs. However, I only want to display a spinner if the data takes longer than 150ms to arrive. Here is how I want the flow on the UI to be: wait for 150ms - if the data arrives, ...

Use jsPDF and jsPDF auto-table to left-align text

I need help with aligning the header to the left in my project where I'm utilizing jspdf and the jspdf-auto table JavaScript library. https://i.sstatic.net/MHIJy.png code const doc = new jsPDF("p", "pt", "a4"); doc.auto ...

Enhance Angular2 by applying global element attributes across your website

As I work on building my Angular2 application, it has become evident that in order to optimize for mobile usage, I need to disable autocomplete, autocorrect, autocapitalize, and spellcheck for all HTML inputs. Instead of manually adding this attribute to e ...

Issue with Socket.IO: socket.on not executed

Recently, I devised a custom asynchronous emitter for implementing a server -> client -> server method. Regrettably, the functionality is not meeting my expectations. Although it emits the event, it fails to execute the callback as intended. Upon a ...

What is the best way to adjust the width of the <span> element in an Angular application?

This snippet showcases a piece of HTML code. <div class="col-md-8"> <span class="label">Product Name</span> <span> <mat-form-field> <input matInput formControlName="productName"> </mat-form ...

What are the best scenarios for creating a constructor in Angular 2 using Typescript?

Check out these sample constructors I found in the Angular 2 documentation: export class AppComponent implements OnInit { title = 'Tour of heroes'; heroes: Hero[]; selectedHero: Hero; constructor(private heroService: HeroService ...

Building a route to a link in Next.js: A step-by-step guide

Having trouble setting up routes to my Next.js portfolio project page. I've created an array of pages and their links in the index.ts file within the data folder, but I'm facing issues with routing. I've integrated a floating navigation usi ...

The specified file cannot be found within the Node file system

I am working on a project that involves reading a file using Node fs, and I have the following code: const files: FileSystemTree = { "Component.tsx": { file: { contents: fs.readFileSync( `../../apps/components ...