Explore the world of data manipulation in Angular by experimenting with different

Embarking on a fresh Angular 2 project centered around Photos and Users.

The backend work is all done, with the API in place. I've already constructed those classes.

Now, I find myself pondering...
To manipulate these objects on the client end, would it be better to rewrite the classes in typescript?

let photo = new Photo(1, "http://url", "Some title");

or simply stick with standard objects?

let photo = {
    id: 1,
    url: "http://...",
    title: "Some title"
}

Which route should I take?

The first option entails duplicating the model (first on server, then on client side).
The second choice feels a bit old-fashioned, doesn't it?

Answer №1

Assuming that your API will return a JSON object containing your data, it is recommended to immediately cast that object into a typed object for better practice. Let's consider the example of a Photo object being retrieved from a Photo API endpoint.

{
    id: 1,
    url: "http://...",
    title: "Some title"
}

To handle this, it would be wise to create an interface for the photo object:

interface Photo {
  id: number,
  url: string,
  title: string
}

Interfaces allow you to define the structure of objects in your application. For instance, if a third-party API returns an object key like 'lstPrc', you can redefine it in your interface as 'lastPrice'!

Now that we have an interface, we can type and construct an object from the API's data:

// Assuming we're in an ajax callback context

function (data) {
  const photo: Photo {
    id: data.id,
    url: data.url,
    title: data.title
  }

   // perform operations with our new typed photo object
}

The advantages of working with a typed object may not be immediately apparent without experience in strongly typed languages. However, you'll reap numerous benefits moving forward in terms of code extension, refactoring, and improved code completion provided by your IDE or text editor.

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

Navbar Growth Effect

I'm attempting to create an expanding effect in my navbar using Angular. When I click on "show information," the content should slide up. The issue is that the top part of my footer does not follow the effect. I have tried something like: <foot ...

Why should we include the '#' character in jhipster URLs?

Standard Angular applications typically do not include a '#' sign in their URLs. However, in JHipster URLs, the '#' character serves a specific purpose. Can you explain the significance of the '#' symbol in JHipster URLs and h ...

What is the best way to check for duplicate email input when using knex?

Currently, I am in the process of developing an application using node.js, knex.js, typescript, zod, and fastify. My main focus is on validating emails during user registration. If a duplicate email is inserted, I want the system to throw a 401 (conflict) ...

Is there a way to set the default timezone for the entire application to something like 'UTC' using JavaScript and Angular?

I'm currently developing a Hotel application where customers communicate using UTC. I have completed most of the work but everywhere I used the date object like so => new Date(). Before running the application, I need to change my local timezone to ...

Should Angular 6 developers consider storing JSON web tokens in LocalStorage or Session Storage?

After doing a lot of research, I have come across various discussions regarding the storing of JSON web tokens in different areas like local storage, session storage, and cookies. Each method has its own advantages and disadvantages that developers conside ...

The issue with Ionic 2 arises when attempting to use this.nav.push() because it

Recently transitioning from Ionic 1 to Ionic 2, I'm encountering an issue with using this.nav.push(nameOftheOtherPage) immediately after a promise. Interestingly, the function this.nav.push works fine when it's called outside of the promise funct ...

NgOnChanges replaces form control value when user inputs text

In my autocomplete form control component: @Component({ selector: 'app-autocomplete', templateUrl: './app-autocomplete.view.html', changeDetection: ChangeDetectionStrategy.OnPush, }) export class AutoCompleteFilterComponent ...

Encountering an error during the building of an AOT compilation due to a jointly used

After creating a shared angular 2 module to organize reusable components, everything was functioning properly. However, the issue arose during the AOT build process with the error message provided below: Error encountered resolving symbol values staticall ...

Testing Slack's Web API with Jest for mock purposes

Currently, I am working with two files. One file is where I set up a slack web API client to post a message and test it with a mocked value: main.ts: import { WebClient } from '@slack/web-api'; const slack = new WebClient(process.env.SLACK_API_K ...

Creating a function in Typescript that transforms an array into a typed object

Recently, I have started learning TypeScript and I am working on a function to convert arrays from a web request response into objects. I have successfully written the function along with a passing unit test: import { parseDataToObject } from './Parse ...

Building a filter for a union type in TypeScript: a step-by-step guide

Allow me to present an example to demonstrate my current objective. const v1: { type: "S"; payload: string } = { type: "S", payload: "test" }; const v2: { type: "N"; payload: number } = { type: "N", payload: 123 }; type Actions = typeof v1 | typeof v2; ...

Dropdown box not displaying any choices

I developed a basic reusable component in the following way: Typescript (TS) import {Component, Input, OnInit} from '@angular/core'; import {FormControl} from '@angular/forms'; @Component({ selector: 'app-select', templa ...

Is it possible to select a tab in Angular 10 Material Tabs based on a route parameter?

My webpage features a mat-tab-group, located at the URL /transactions. <mat-tab-group> <mat-tab label="Shipments"> <ng-template matTabContent> shipment content </ng-template> ...

What is the correct way to integrate knex using inversify?

Is there a way for me to set up knex and utilize the Inversify dependency injector to inject it wherever it is required? ...

Alter the language settings of the Datepicker feature in Material Angular 4

Need help changing the language of Datepicker in Material Angular. Struggling to locate this information in the Angular material 2 documentation. Check out this plunkr https://plnkr.co/edit/unzlijtsHf3CPW4oL7bl?p=preview <md-input-container> < ...

Repeatedly view the identical file on HTML

I'm currently working with the following HTML code: <input type="file" style="display: none" #file(change)="processImage($event)" /> <button type="button" class="btn" (click)="file.click()" Browse </button> When I select image1 fr ...

Troubleshooting: Issues with Angular 2 Dependency Injection

I am facing an issue with my angular2 application that involves a simple dependency injection, but it seems to be not working correctly. Can anyone help me figure out what might be missing? Below is the error message I am encountering: EXCEPTION: Cannot ...

Error: Local variable remains undefined following an HTTP request

Whenever I make http calls, my goal is to store the received JSON data in a local variable within my component and then showcase it in the view. Service: getCases(){ return this.http.get('someUrl') .map((res: Response) => res.jso ...

Oops! NG0900 error occurred while attempting to differentiate '[object Object]'. Please note that only arrays and iterables are permissible, so please stick to using observables and subscribe methods

Struggling to fetch data from an API and pass it to a component for use in a table, but encountering the same issue repeatedly. The data is visible, yet there seems to be a glitch. Here's a snippet from my console: enter image description here Snipp ...

Exploring Objects with Union Types in TypeScript

Looking to iterate through an object that combines two interfaces. interface Family { cat: string; age: string; family: string; lastYearFamily: string; } interface Model { cat: string; age: string; ...