如何从HTTP响应转换为我可以在Typescript中使用的对象?

问题描述 投票:0回答:2

如您所见,我是新用户。通过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文件的另一种方法中使用它。

angular
2个回答
0
投票

我可能在编辑之前误解了这个问题,希望我的回答会有所帮助。如果没有,则为策略。


不幸的是,无法自动执行您想要的操作。

您将需要手动将服务返回的普通JavaScript对象映射到City类的实例。

最好在getCity方法中执行此映射:

return this.httpClient.get(CITY_URL)
  .pipe(
    map(plainOldJavascriptObject => new City(...))
  );

或者,如果City类没有行为(即函数),则最好使用接口,在这种情况下,不需要映射。


0
投票

如果我说对了,您只需要键入响应?

  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();
  }
© www.soinside.com 2019 - 2024. All rights reserved.