Angular 4: Utilizing a class with a constructor to create an http Observable model

Within my application, I have a Class model that is defined with a constructor. Here is an example:

export class Movie {
    title: string;
    posterURL: string;
    description: string;

    public constructor(cfg: Partial<Movie>) {
        Object.assign(this, cfg);
    }

    getEndDate(): Date {
        return new Date();
    }
};

Additionally, I have an HTTP request that utilizes this model

getMoviesData(): Observable<Movie[]> {
    return this.http.get<Movie[]>(`http://localhost:3544/movies`)
}

As anticipated, there seems to be an issue

What steps can I take to resolve this matter? Do I need to create an interface as well?

Thank you for your assistance :)

Answer №1

HTTPClient functions are universal, with this.http.get<Film[]> ensuring that the output adheres to the Film[] structure without creating new Film objects.

To convert the output into object instances, it is necessary to explicitly instantiate a class. The class constructor should ideally accept a simple object whose properties will be assigned to an instance of the class. With the Film class, this is achieved through the cfg parameter.

Instead of relying solely on the Partial<Movie> type which may not fully describe the interface, it would be advisable to define a distinct interface:

interface IFilm {
    title: string;
    posterURL: string;
    description: string;
}

class Film implements IFilm { ... }

...

getFilmData(): Observable<Film[]> {
    return this.http.get<IFilm[]>(...)
    .map(rawFilms => rawFilms.map(rawFilm => new Film(rawFilm)))
}

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

ability to reach the sub-element dictionaries in typescript

class ProvinciaComponent extends CatalogoGenerico implements OnInit, AfterViewInit { page: Page = new Page({sort: {field: 'description', dir: 'asc'}}); dataSource: ProvinciaDataSource; columns = ['codprovi ...

How to incorporate HTML 5 video into your Angular 2 project using Typescript

How can I programmatically start an HTML video in TypeScript when the user clicks on the video area itself? Below is my HTML code: <div class="video"> <video controls (click)="toggleVideo()" id="videoPlayer"> <source src="{{videoSource ...

Tips for Invoking an Overloaded Function within a Generic Environment

Imagine having two interfaces that share some fields and another interface that serves as a superclass: interface IFirst { common: "A" | "B"; private_0: string; } interface ISecond { common: "C" | "D"; private_1: string; } interface ICommo ...

Using Angular and Typescript to Submit a Post Request

I am working on a basic Angular and Typescript page that consists of just one button and one text field. My goal is to send a POST request to a specific link containing the input from the text field. Here is my button HTML: <a class="button-size"> ...

The error message "Property 'data1' is not a valid property on the object type {}"

const Page: NextPage = ({data1}:{data1:any}) => { const [open, setOpen] = React.useState(false); const [data, setData] = React.useState(data1); const handleAddClick = () => { setOpen(true); }; ..... } export async function getServerS ...

experimenting with the checked attribute on a radio button with jasmine testing

Currently using Angular 8 with Jasmine testing. I have a simple loop of radio buttons and want to test a function that sets the checked attribute on the (x)th radio button within the loop based on this.startingCarType. I am encountering false and null tes ...

Next.js is faced with a frustrating issue where images and videos are failing to display

I've been working on my Next.js 13 project with TypeScript, eslint, and Chakra UI, but I'm facing an issue with images and videos not displaying. Despite trying both the HTML <img> tag and importing Image from Chakra, the problem still per ...

Encountering a 401 error when trying to access OneNote resource in Angular 5 with Microsoft Graph

I have encountered an issue while trying to request resources from Microsoft graph (for OneNote API). My concern revolves around the correct method of obtaining an access token. I am utilizing the implicit flow for my Angular 5 frontend application. The p ...

What is preventing the mat-slide-toggle from being moved inside the form tags?

I've got a functioning slide toggle that works perfectly, except when I try to move it next to the form, it stops working. When placed within the form tag, the toggle fails to change on click and remains in a false state. I've checked out other ...

Discover the latest DOM elements using Webdriverio 5

Currently, I am developing a REact based CMS application that features a form with multiple carousels. I am encountering an issue where the webdriverio implementation is unable to locate an element, even though the same xpath works fine when tested manua ...

When using Typescript, I am encountering an issue where declared modules in my declaration file, specifically those with the file

One of the declarations in my ./src/types.d.ts file includes various modules: /// <reference types="@emotion/react/types/css-prop" /> import '@emotion/react'; import { PureComponent, SVGProps } from 'react'; declare mod ...

learning how to transfer a value between two different components in React

I have 2 components. First: component.ts @Component({ selector: "ns-app", templateUrl: "app.component.html", }) export class AppComponent implements OnInit { myid: any; myappurl: any; constructor(private router: Router, private auth: ...

The Nextjs application folder does not contain the getStaticPaths method

I encountered a problem with the latest nextjs app router when I tried to utilize SSG pages for my stapi blog, but kept receiving this error during the build process app/blog/[slug]/page.tsx Type error: Page "app/blog/[slug]/page.tsx" does not m ...

TS2367: Given any input, this condition will consistently evaluate to 'false'

I'm struggling to understand why the compiler is not including null as a possible type for arg, or perhaps I am misinterpreting the error message. static vetStringNullable(arg:any): string|null { if (typeof arg === 'string') { ...

"Encountered a type error with the authorization from the credentials provider

Challenge I find myself utilizing a lone CredentialsProvider in next-auth, but grappling with the approach to managing async authorize() alongside a customized user interface. The portrayal of the user interface within types/next-auth.d.ts reads as follo ...

The 'validate' property within the 'MappingService' class cannot be assigned to the 'validate' property in the base class 'IMappingService' in typescript version 2.8.0

Currently, I am utilizing the AngularJS framework (version 1.5.8) in tandem with the latest TypeScript files (2.8.0). However, upon updating to the newest version of TypeScript, the code below is failing to compile. The IMappingService interface: export ...

Angular Boilerplate is experiencing difficulties in properly reading ABP

Working on my boilerplate project, I am now diving into consuming backend services (using asp .net) in Angular through http requests. However, I encountered an issue when trying to implement the delete method in mycomponent.ts, as TypeScript was not recogn ...

Guide on uploading an image to Azure Blob Storage using v10 SDK

Currently, I am attempting to upload an image to the Blob Storage in Microsoft Azure using SDK V10 within an Angular framework. The code snippet below demonstrates how I establish a connection to the Storage and retrieve the names of all containers: // E ...

Item removed from the cache despite deletion error

Currently, I am utilizing Angular 8 along with @ngrx/data for handling my entities. An issue arises when a delete operation fails (resulting in a server response of 500), as the entity is being removed from the ngrx client-side cache even though it was not ...

Enroll a nearby variable "Data" to an Observable belonging to a different Component within an Angular application

Looking to update the HTML view using *ngIf, depending on a local variable that should change based on an observable variable from a shared service. HTML <div class="login-container" *ngIf="!isAuthenticated"> TypeScript code for the same componen ...