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

Tips for reverting from Angular 7 to Angular 6

I attempted to switch from angular 7 back to angular 6 by executing the following npm commands: npm uninstall -g angular-cli npm cache clean npm install -g <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="32535c55475e53401f515e5 ...

Using Vue js and Typescript to automatically scroll to the bottom of a div whenever there are changes in

My goal is to automatically scroll to the bottom of a div whenever a new comment is added. Here's what I have been trying: gotoBottom() { let content = this.$refs.commentsWrapper; content.scrollTop = content.scrollHeight } The div containing ...

Having trouble with implementing custom checkboxes in a d3 legend?

My attempt at creating checkboxes in d3 has hit a snag. Upon mouse click, the intention is for them to be filled with an "x". Strangely, using d3.select() inside the click-function doesn't seem to work as expected, although adding the letter U for the ...

Implementing Angular functionality with Bootstrap's collapse component

I am currently learning Angular and experimenting with two collapsible div elements. My goal is to have element-1 collapse and element-2 hide when button1 is clicked. Conversely, when button2 is clicked, I want element-2 to collapse and element-1 to hide. ...

Expanding User Type to Include Extra User Data Using NextAuth.js

I encountered a dilemma where I needed to include the "profile" property in my section object to cater to different user personas in my application. However, despite retrieving the logged-in user's data from the backend and storing it in the NextAuth. ...

Experimenting with a function that initiates the downloading of a file using jest

I'm currently trying to test a function using the JEST library (I also have enzyme in my project), but I've hit a wall. To summarize, this function is used to export data that has been prepared beforehand. I manipulate some data and then pass it ...

Ways to address the issue arising from the utilization of the "as" keyword

Every time I encounter this issue - why must I always provide all the details? type Document = Record<string, any> type FilteredDocument<T extends Document> = {[key in keyof T as T[key] extends (()=>void) ? never : key]: T[key]} const ...

Tips for receiving @ mentions in PrimeNg Editor using Quill and quill-mention with Angular

Currently, I have been given the task of adding a mentions feature to our text editors. The editor I am working with is the PrimeNg Editor, built on Quill. After some research, I came across the package quill-mention, which appears to be a potential soluti ...

What is the best approach to handling an undefined quantity of input FormControls within Angular?

I have a unique task in my Angular application where I need to collect an unspecified number of entries, such as names, into a list. My goal is to convert this list of names into an array. To facilitate this process, I would like to offer users the abilit ...

Difficulty in detecting variable modifications during testing - Angular2+

After successful login, I expect a certain variable to be updated with the appropriate value. However, during testing, all I see is 'undefined' returned. This variable does change when interacting with the app, showing an error message like &apo ...

Oops! An error occurred: Validation Error - Unable to convert value to ObjectID

SCENARIO: It appears that there might be an error in my Mongoose Model or in the parameters being passed to the route. As a newcomer to the angular2 architecture, I may have overlooked something obvious. ISSUE: ISSUE: ValidationError: CastError: Cas ...

In Angular, there is an issue where the @ViewChild decorator does not reflect changes when the value of the child component is updated within the

Does anyone know why the console.log("My status :", status); is not displaying after the child property has changed? Here is my child component code: @Output() public isLoggedIn: Subject<boolean> = new Subject(); constructor( private auth ...

I'm trying to figure out the best way to successfully pass a prop to another component in TypeScript without running into the frustrating issue of not being able to

I have been facing an issue while trying to pass a prop from a custom object I have defined. The structure of the object is as follows: export type CustomObjectType = { data?: DataObject }; export type DataObject = { id: number; name: stri ...

Is NATS.io compatible with React Native?

Struggling with integrating nats.io into a React Native project using Typescript has presented many challenges. Is there a way to successfully incorporate it without having to modify node_modules of nats (such as changing the "fs" import to "react-native-f ...

How can I make the snackbar open multiple times in a row?

Check out this codesandbox I created to show an issue. When you click the button, a MUI snackbar opens. However, if you close it and try to reopen it, nothing happens. Do you think the problem is related to how I'm using hooks? Explore the sandbox h ...

Utilize an external JavaScript function within a React and TypeScript document

I have encountered an issue in my React/Next.js/TypeScript file where I am trying to load the YouTube iframe API in my useEffect hook. Here is the code snippet: useEffect(() => { const tag = document.createElement('script'); tag.src = ...

What is the method to retrieve the total number of days in a moment-jalaali using NodeJS?

I'm trying to determine the number of days in the moment-jalaali package for NodeJS. Despite checking their API on GitHub, I couldn't find any reference to a specific method like numOfDay. ...

The connection to Firebase is being refused when attempting to use the http.post method in Ionic

In my Ionic 3 Angular app deployed on Firebase static hosting, the problematic section of code appears as follows: var data = {"message" : time, "user_id" : user}; return new Promise((resolve, reject) => { ...

Is a shallow copy created by spreading?

According to the example provided in the documentation, let first:number[] = [1, 2]; let second:number[] = [3, 4]; let both_plus:number[] = [0, ...first, ...second, 5]; console.log(`both_plus is ${both_plus}`); first[0] = 20; console.log(`first is ${firs ...

Using React's higher order component (HOC) in TypeScript may trigger warnings when transitioning from non-TypeScript environments

I have a simple HOC component implemented in React with TypeScript. export const withFirebase = <P extends object>( Component: React.ComponentType<P> ) => class WithFirebase extends React.Component<P> { render() { return ...