2
votes

How to initialize an object inside an object and array-object in angular service class? I want to use the two-way binding into my-form, so I want to pass the variable from service class to Html template.

trainer.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

import { Trainner } from '../trainner.model';
import { Observable } from 'rxjs';

const headerOption = {
 headers : new HttpHeaders({'Content-Type': 'application/json'})
};

@Injectable({
  providedIn: 'root'
})

  export class TrainnerService {
     selectedTrainer: Trainner;
      _url = 'http://localhost:3000/trainner';

  constructor( private _http: HttpClient ) { }

  register(registrationFormData) {
    return this._http.post<any>(this._url, registrationFormData);
  }

  getAllTrainner(): Observable<Trainner[]> {
    return this._http.get<Trainner[]>(this._url, headerOption);
  }

  putTrainner(trainer : Trainner): Observable<Trainner[]> {
    return this._http.put<Trainner[]>(this._url + `/$(emp._id)`, trainer);
  }
}

I have model.ts file

export class Trainner {
personal_details: { type: Object,
    name: { type: Object,
        first_name: String,
        last_name: String
    },
    dob: String,
    about_yourself: String,
    languages_known: { type: Array<Object>,
        items: {
            type: String
        }
    },
    willingly_to_travel: String
};

}
1
map method could help you. - ngShravil.py
can you show me some syntax @ngShravil.py - GRV
Which variable exactly is the one you need to initialize? - Lahiru Chandima
As you can see i have a model.ts file, so I need to initialize that particular modal so that i can use two-way binding when an update event occurs @LahiruChandima - GRV

1 Answers

1
votes

you can create multiple model classes. you can update the current model and create a TrainerName.ts class that holds the name object and Language.ts that holds the language object. like this:

export class TrainerName{
 first_name: String,
 last_name: String
}

and Language model class like :

export class Language {
items:  String       
}

and use it in your current model class like:

export class Trainner {
personal_details: { type: Object,
    name: TrainerName,
    dob: String,
    about_yourself: String,
    languages_known: Language[],
    willingly_to_travel: String
};

}

and in your service you can use map

getAllTrainner(): Observable<Trainner[]> {
    return this._http.get<Trainner[]>(this._url, headerOption).map(res => new Trainner(res));
  }