K
K
kachurinets2018-07-13 18:04:30
JavaScript
kachurinets, 2018-07-13 18:04:30

Angular: How to destruct code in data model constructor?

There is such a class

export class Street {
    glob_id: string;
    id: string;
    is_edited: string;
    parents_levels: Array<number>;
    parents_names: Array<string>;
    name: string;
    region_id: string;
    region: string;
    county: string;
    area: string;
    city: string;
    city_district: string;
    place: string;
    street: string;
    additional_territory: string;
    additional_territory_subject: string;
    constructor(street?) {
        street = street || {};
        this.glob_id = street.glob_id || '';
        this.id = street.glob_id || '';
        this.is_edited = street.is_edited || '';
        this.name = street.name || '';
        this.parents_names = JSON.parse(street.parents_names) || [];
        this.parents_levels = JSON.parse(street.parents_levels) || [];
        this.region_id = street.region_id || [];


        for (let i = 0; i < this.parents_levels.length; i++) {
            switch (+this.parents_levels[i]) {
                case 1:
                    this.region = this.parents_names[i];
                    break;
                case 2:
                    this.county = this.parents_names[i];
                    break;
                case 3:
                    this.area = this.parents_names[i];
                    break;
                case 4:
                    this.city = this.parents_names[i];
                    break;
                case 5:
                    this.city_district = this.parents_names[i];
                    break;
                case 6:
                    this.place = this.parents_names[i];
                    break;
                case 90:
                    this.additional_territory = this.parents_names[i];
                    break;
                case 91:
                    this.additional_territory_subject = this.parents_names[i];
                    break;
            }
        }

    }
}

The thing is that you need to make a few more entities, for example City, Region, etc. In each entity, the switch case construction is repeated. How can I avoid code duplication? I thought to bring this function into a service, but I have not yet seen such that the service is injected into the model constructor? How to do it right?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
NeoSimvolist, 2018-07-21
@NeoSimvolist

The correct way is not to block the logic in the model, but to take it out to the manager (aka service). The model itself should be kept extremely simple, with a maximum of calculated fields. Each model has its own manager. And when you need connections between models, you will inject managers into managers. Believe me, this approach will pay off with the development of the project.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question