Home > Enterprise >  Create instance of class from object returned by api call
Create instance of class from object returned by api call

Time:03-10

I am retrieving an Object from a mongoose api, and I need to turn it into an instance of a custom class. Currently I have it set up to manually pass the Object's members into the constructor of the Ingredient class to create a new Ingredient like so:

ingredient.model.ts:

export class Ingredient {
    quantity: number;
    unit: string;
    description: string;
    ...

    constructor(quantity: number, unit: string, description: string, ...) {
        this.quantity = quantity;
        this.unit = unit;
        this.description = description;
        ...
    }
}

someComponent.component.ts:

import { Ingredient } from "ingredient.model.ts"

foo: Ingredient;

ngOnInit() {
    api.getIngredient(id).subscribe((ingredient) => {
        this.foo = ingredient;
    });

    let newIngredient = new Ingredient(foo.quantity, foo.unit, foo.description, ...)
}

I'm sure there's a much cleaner way to do this that allows me to avoid tediously assigning each member. I'm wanting to something along the lines of this with a constructor that just "magically" converts the object to an instance of Ingredient:

api.getIngredient(id).subscribe((ingredient) => {
    let newIngredient = new Ingredient(ingredient);
});

CodePudding user response:

Your Model

export class Ingredient {
    quantity: number;
    unit: string;
    description: string;

    constructor(data?) {
        data = data || {};
        this.quantity = data.quantity;
        this.unit = data.unit;
        this.description = data.description;
    }
}

Your Component

import { Ingredient } from "ingredient.model.ts"

foo: Ingredient;

ngOnInit() {
    this.foo = new Ingredient({});
    api.getIngredient(id).subscribe((ingredient) => {
        this.foo = new Ingredient(ingredient);
    });

    let newIngredient = new Ingredient(this.foo)
}

CodePudding user response:

Why don't you use an interface and getIngredient returns an Observable<Ingredient>?

Example:

Ingredient Interface

export interface Ingredient {
    quantity: number;
    unit: string;
    description: string;
    ...
}

API Service

public getIngredient(id: string | yourType): Observable<Ingredient> {
  .... 
  return httpService.get<Ingredient>(...);
}

Component

api.getIngredient(id).subscribe((ingredient) = this.foo = ingredient);

In this way, you are telling that the response of getIngredient is an Ingredient interface and you don't need the assign the property.

Of course this is valid only if you don't have any methods inside Ingredient, otherwise you have to switch to class but the logic is the same

  • Related