Using Angular 5 with Typescript to generate and return an array of freshly instantiated typed objects

My backend service provides me with "moments," and I have two functions to handle this data. One is a get() method that returns a single object, and the other is a search() method that returns an array of objects.

moment.service.ts

The get method successfully maps the response from the backend to create a new instance of my Moment class.

   get(moment_id) {

        let endpoint = this.path + moment_id;

        return this.apiService.get(endpoint)
                              .map((res) => new Moment(res.data));
    }

I want to achieve the same result in the search method, where each object in the array should be a new instance of the Moment class.

search(filters) {

    let endpoint = this.path + 'search';

    let params = new HttpParams({ fromObject: filters });

    return this.apiService.get(endpoint, params)
                          .map((res) => new Array<Moment>(res));
}

Unfortunately, the above approach does not indicate that the objects in the returned array are of type Moment.

https://i.stack.imgur.com/v0NnA.png

moment.component.ts

   moments: Moment[] = [];

    this.momentService.search(filters).subscribe((res) => {
                this.moments = res;
                console.log(this.moments);
            });

moment.model.ts

import { Comment } from './comment.model';
import { User } from './user.model';

export class Moment {

    _id?: string = null;
    body?: string = null;
    author?: User = null;
    likes?: any[] = [];
    dislikes?: any[] = [];
    comments?: Comment[] = [];
    created_at?: string = null;
    updated_at?: string = null;


    constructor(data?: Moment) {
        if (data) {
            this.deserialize(data);
        }
    }

    private deserialize(data: Moment) {

        const keys = Object.keys(this);
        for (const key of keys) {
            if (key === 'author') {
                this[key] = new User(data['author']);
            } else if (key === 'comments') {
                this[key] = data['comments'].map(c => new Comment(c));
            } else {
                this[key] = data[key];
            }
        }
    }
}

Answer №1

To instantiate moments quickly, use the following method:

fetchMoments(filters) {
    let endpoint = this.baseUrl + 'fetch';
    let params = new HttpParams({ fromObject: filters });
    
    return this.apiService.get(endpoint, params)
                          .map((response) => new Array<Moment>(new Moment(response)));
}

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

Handling HTTP Errors in Angular Components with NGRX

I have successfully integrated the store into my angular project. I am able to handle and process the successSelector, but I am facing difficulty in capturing any data with the errorSelector when an HTTP error occurs from the backend. The error is being c ...

A guide to adding a delay in the RxJS retry function

I am currently implementing the retry function with a delay in my code. My expectation is that the function will be called after a 1000ms delay, but for some reason it's not happening. Can anyone help me identify the error here? When I check the conso ...

Using Typescript to create an interface that extends another interface and includes nested properties

Here is an example of an interface I am working with: export interface Module { name: string; data: any; structure: { icon: string; label: string; ... } } I am looking to extend this interface by adding new properties to the 'str ...

Having trouble getting anime.js to function properly in an Ionic 3 project?

I have been attempting to incorporate anime.js into my Ionic 3 project, but I keep encountering an error when using the function anime({}) in the .ts file. Error: Uncaught (in promise): TypeError: __webpack_require__.i(...) is not a function TypeError: _ ...

When using the map function, I am receiving an empty item instead of the intended item based on a condition

Need assistance with my Reducer in ngRx. I am trying to create a single item from an item matching an if condition, but only getting an empty item. Can someone please help me out? This is the code for the Reducer: on(rawSignalsActions.changeRangeSchema, ...

Encountering issues in d3.js following the transition to Angular 8

After upgrading my Angular 4 app to Angular 8, I encountered an issue where the application works fine in development build but breaks in production build. Upon loading the application, the following error is displayed. Uncaught TypeError: Cannot read p ...

Looking for a way to display a spinner loader while transitioning between routes in Angular 4? Although I'm receiving events, I'm struggling to actually show the loader on screen

I'm currently working on a project that requires a loader to display between two routes. Although I am receiving route events, the loader is not visible. import { Component } from '@angular/core'; import { Router, Event, NavigationStart, Na ...

Generating GraphQL Apollo types in React Native

I am currently using: Neo4J version 4.2 Apollo server GraphQL and @neo4j/graphql (to auto-generate Neo4J types from schema.graphql) Expo React Native with Apollo Client TypeScript I wanted to create TypeScript types for my GraphQL queries by following th ...

Show JSON information in an angular-data-table

I am trying to showcase the following JSON dataset within an angular-data-table {"_links":{"self":[{"href":"http://uni/api/v1/cycle1"},{"href":"http://uni/api/v1/cycle2"},{"href":"http://uni/api/v1/cycle3"}]}} This is what I have written so far in my cod ...

What could be causing my Page to not update when the Context changes?

In my Base Context, I store essential information like the current logged-in user. I have a User Page that should display this information but fails to re-render when the Context changes. Initially, the Context is empty (isLoaded = false). Once the init fu ...

Discrepancy in Angular Material Buttons with theme design

I recently installed Angular 10 along with Angular Materials using the command ng add @angular/material I opted for the custom theme: Purple/Green The next step was to add a Toolbar by simply copying and pasting code from Google's site. However, I a ...

Creating a data structure that filters out specific classes when returning an object

Consider the following scenario: class MyClass {} class MyOtherClass { something!: number; } type HasClasses = { foo: MyClass; bar: string; doo: MyClass; coo: {x: string;}; boo: MyOtherClass; }; type RemovedClasses = RemoveClassTypes& ...

Manipulating variables across various methods in TypeScript

I have a simple code snippet where two variables are defined in the Main method and I need to access them from another method. However, I am encountering an issue with 'variables are not defined', even though I specified them in the declerations ...

Creating conditional observable debounceTime

I've implemented a basic debounce on an input element event in the following way: Observable .fromEvent(this.elInput.nativeElement, 'input') .debounceTime(2000) .subscribe(event => this.onInput(event)); Is there ...

Typical approach to receiving a transformed object from an HTTP service

One of the services I provide includes a method with the following implementation: public fetchCrawls(page: number): Observable<ICrawl[]>{ return this._http.get(this._crawlsURL + page) .map((res: Response) => { ...

Vue 3 Composable console error: Unable to access properties of undefined (specifically 'isError') due to TypeError

I recently developed a Vue 3 / TypeScript Composable for uploading images to Firebase storage. The code snippet below illustrates the structure of the ImageUpload interface: interface ImageUpload { uploadTask?: UploadTask; downloadURL?: string; progr ...

A guide on incorporating ng2-canvas-whiteboard into your Ionic 3 project

I'm trying to implement the npm package ng2-canvas-whiteboard into my Ionic 3 app. I followed all the instructions on the npm page and here is my package.json: "dependencies": { "@angular/common": "4.0.2", "@angular/compiler": "4.0.2", ...

Angular route fails to load the HTML file

In the process of developing a route within an Angular application, I have successfully implemented 3 routes. However, one particular route is giving me trouble. I have three folders that need to redirect HTML based on the option chosen. In Angular, I cre ...

I require assistance in displaying a dynamic, multi-level nested object in HTML using AngularJS

I have a complex dynamic object and I need to extract all keys in a nested ul li format using AngularJS. The object looks like this: [{"key":"campaign_1","values":[{"key":"Furniture","values":[{"key":"Gene Hale","values":[{}],"rowLevel":2},{"key":"Ruben A ...

Add the slide number and total count in between the navigation arrows of the owl carousel

In my Angular application, I am utilizing an ngx owl carousel with specific configurations set up as follows: const carouselOptions = { items: 1, dots: false, nav: true, navText: ['<div class='nav-btn prev-slide'></div>' ...