如您所见,我是新用户。通过ngSubmit提交表单时,我有一个HTTP响应。我想使用该响应并将其用作对象,以便可以在Typescript文件中重复使用此对象。
Map.html
<form [formGroup]="originCityForm" (ngSubmit)="getOriginCity(originCityForm)">
<input
matInput
type="text"
placeholder="Origin city"
formControlName="origin"
/>
</form>
Map.ts
originCity : City;
ngOnInit() {
this.originCityForm = this.fb.group({
origin: ['', [Validators.required, Validators.pattern('[a-zA-Z ]*')]]
});
this.originCity = new City();
}
getOriginCity(originCityForm: FormGroup) {
const o = new City();
this.service.getCity(originCityForm.value.origin).subscribe(
city => {
o.id = city.id;
o.title = city.title;
o.latitude = city.latitude;
o.longitude = city.longitude;
o.destination = city.destination;
},
error => console.log(error)
);
console.log(o); // It will print the request response as an object (Which is what I want)
originCityForm.reset();
}
ngAfterViewInit() {
this.zone.runOutsideAngular(() => {
console.log(this.originCity) // When I print, this.originCity is null
}
我收到了预期的回复。但是,我不知道如何获取此响应并将其设为对象City,以便可以在Typescript文件的另一种方法中使用它。
我可能在编辑之前误解了这个问题,希望我的回答会有所帮助。如果没有,则为策略。
不幸的是,无法自动执行您想要的操作。
您将需要手动将服务返回的普通JavaScript对象映射到City类的实例。
最好在getCity
方法中执行此映射:
return this.httpClient.get(CITY_URL)
.pipe(
map(plainOldJavascriptObject => new City(...))
);
或者,如果City
类没有行为(即函数),则最好使用接口,在这种情况下,不需要映射。
如果我说对了,您只需要键入响应?
originCity: City;
getOriginCity(originCityForm: FormGroup) {
this.service.getCity(originCityForm.value.origin).subscribe(
(city:City) => {
console.log(city);
this.originCity = city;
},
error => console.log(error)
);
originCityForm.reset();
}