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

Having an issue where the Material Angular 6 DatePicker is consistently displaying my selected date as one day earlier

I've encountered a strange issue with the current version of the Material Angular DatePicker. After upgrading from A5 to A6, it started to parse my date one day earlier than expected. You can see an example of this problem here: https://stackblitz.com ...

Angular doesn't support this particular type as an injection token

I'm attempting to create a constructor with a type of string, but I keep encountering the following error: This particular type is not supported as an injection token @Injectable({providedIn: 'root'}) export class DataService { const ...

The formBuilder validator pattern seems to be malfunctioning

I am attempting to display a message when the password does not meet the formGroup pattern. Here is how my FormGroup is initialized: this.signupForm = fb.group({ userName: ['', Validators.compose([Validators.required,Validators.pattern(/^&bsol ...

I am facing an issue with Angular reactive forms where the default values I set in ngOnInIt are not being reflected

Having some issues with setting default values in my Angular app using reactive forms. The defaults I set in ngOnInit are not showing up. I am also using the filter function within the map method. I am trying to select a value based on the URL and have it ...

Testing the automation processes of a React or Node project

I am currently working on a project developed using React, Node.js, and MongoDB. I am looking to create an automation test that will automatically fill in either the login or register form. If anyone has any ideas or suggestions, please share them with m ...

Tips for positioning a div alongside its parent div

I have a unique setup with two nested divs that are both draggable. When I move the parent div (moveablecontainer), the child div (box.opened) follows smoothly as programmed. Everything works well in this scenario. However, when I resize the browser windo ...

Encountering an unforeseen exception in the intercom system

After updating my Angular 13 app to version 17, I encountered the following error. How can this issue be fixed? Error: Unexpected value 'IntercomModule' imported by the module 'AppModule'. Please add an @NgModule annotation. ng-interc ...

What is the best way to convert the NextJS router.query.id to a string?

As a newcomer to TypeScript and the T3 stack (React Query / Tanstack Query), I am facing an issue with typing companyId as string. I want to avoid having to type companyId as string every time I use it in my code, but I'm struggling to find the best p ...

Steps to pass an injection token into a component's constructor during unit testing

In my code, I have an injection token that looks like this: export const IS_SEO_PAGE = new InjectionToken<boolean>('accommodation.seo'); I am using it in a component like this: constructor(@Inject(IS_SEO_PAGE) private isSeo: boolean, Ho ...

Can you explain the rule known as the "next-line" in TypeScript?

No code examples are available for the specific scenario described below: "next-line": [ true, "check-catch", "check-finally", "check-else", "check-open-brace", "check-whitespace" ], ...

Managing a Angular HTTP Request on a Bottle Server where CORS is restricted

I am encountering an issue while trying to send data from my Angular 9 App to a bottle backend server. When running the application on the client side, I receive a CORS (Cross-Origin Resource Sharing) error indicating that the 'Access-Control-Allow-Or ...

Is there a way to utilize Angular in identifying whether a given value corresponds with the value of a particular radio button within my application?

I have an array of lists that I need to display in radio buttons. Like this: https://i.stack.imgur.com/cmYgO.png https://i.stack.imgur.com/Zx4bm.png https://i.stack.imgur.com/jBTe3.png My goal is to have a checkbox that matches the values loaded from a ...

Error in AWS Lambda: Module 'index' not found

In my setup, I have kept it simple by using typescript. All my typescript files are compiled into a /dist directory. Debugging with Webstorm is smooth as it easily finds the handler: The problem arises when I try to run it, leading to this error: 2021- ...

Angular 8: How to Retrieve Query Parameters from Request URL

Can I retrieve the GET URL Query String Parameters from a specific URL using my Angular Service? For example, let's say I have a URL = "http:localhost/?id=123&name=abc"; or URL = ""; // in my service.ts public myFunction(): Observale<any> ...

Angular is unable to display Observable userdataof any type in an asynchronous task

My home component's HTML is not displaying my userData: <h1 class="display-4">Hello, {{ (userData | async)?.username }}</h1> This is the call in home.component.ts: ngOnInit(): void { this.userData = this.userService.getUser(); } ...

Angular 11 is throwing an error stating that the type 'Observable<Object>' is lacking certain properties as required by its type definition

My code is producing the following error: TS2739 (TS) Type 'Observable<Object>' is missing the following properties from type 'WeatherForecast': ID, date, temperatureC, temperatureF, summary I'm puzzled as to why this error ...

There seems to be an issue with the request header field Authorization, as it is not permitted by the Access-Control-Allow-Headers in

My project involves using Angular 2 for the client side and Laravel 5.4 for the server side. I have set up APIs in Laravel and am making requests to them from Angular 2. In Laravel, I have configured Oauth 2 passport service to authenticate all APIs. For ...

Utilizing ngModel with Angular 2 select elements

I am struggling with figuring out how to store the selected value in an object or array. When I select a value from the first selector, I want it to be stored as an object with the first selection. If I select a value from the second selector, I want two ...

Validation in Sync with Angular 2's Latest Version

Encountering the error 'Expected validator to return Promise or Observable' when trying to implement a custom synchronous validator using FormControl and FormGroup classes for validation. The transition from beta to final release has been baffli ...

challenge communicating between Angular and Node using CORS plugin

I've been researching how to enable CORS in node/express and have tried implementing various solutions, but without any success. Here is my angular request: function getPhotos(location) { var url = 'https://api.instagram.com/v1/media/sear ...