如何在角度服务类中初始化对象,数组和对象数组? [英] How to initialize object, array and object-array in angular service class?
问题描述
如何在角度服务类的对象和数组对象内部初始化对象?我想在我的表单中使用双向绑定,所以我想将变量从服务类传递到HTML模板.
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
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);
}
}
我有model.ts文件
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
};
}
推荐答案
,您可以创建多个模型类.您可以更新当前模型并创建保存名称对象的 TrainerName.ts
类和保存语言对象的 Language.ts
.像这样:
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
}
和 Language
模型类,如:
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
};
}
,在您的服务中,您可以使用 map
and in your service you can use map
getAllTrainner(): Observable<Trainner[]> {
return this._http.get<Trainner[]>(this._url, headerOption).map(res => new Trainner(res));
}
这篇关于如何在角度服务类中初始化对象,数组和对象数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!