Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 如何将HTTP响应转换为可以在Typescript中使用的对象?_Angular - Fatal编程技术网

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

Angular 如何将HTTP响应转换为可以在Typescript中使用的对象?,angular,Angular,正如你所看到的,我是一个新用户。当我通过ngSubmit提交表单时,我有一个HTTP响应。我想使用该响应并将其用作对象,以便在我的Typescript文件中重复使用该对象 Map.html <form [formGroup]="originCityForm" (ngSubmit)="getOriginCity(originCityForm)"> <input matInput type="text" placeholder="Origin c

正如你所看到的,我是一个新用户。当我通过ngSubmit提交表单时,我有一个HTTP响应。我想使用该响应并将其用作对象,以便在我的Typescript文件中重复使用该对象

Map.html

<form [formGroup]="originCityForm" (ngSubmit)="getOriginCity(originCityForm)">
   <input
     matInput
     type="text"
     placeholder="Origin city"
     formControlName="origin"
   />
 </form>
我收到了我期望的回应。但是,我不知道如何接受此响应并将其设置为对象城市,以便在Typescript文件中的另一种方法中使用它。

在编辑之前,我可能误解了这个问题,希望我的回答有帮助。抱歉,如果不是的话


不幸的是,没有办法自动做你想做的事情

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

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

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

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

如果我没说错,您只需要键入response

  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();
  }

我想按照你们的建议使用这个界面,但我不知道如何使用。下面是代码:``导出接口城市{id:string;title:string;纬度:数字;经度:数字;目的地:城市;}getCity(title:string){返回this.http.get(this.baseUrl+'/api/'+title).pipe(响应=>new City());}```不能将
new
运算符与TypeScript接口一起使用,只能使用类。在上面的示例中,不需要调用
new City()
。事实上,您应该能够删除整个
.pipe(response=>newcity())
。(这个语法看起来不太正确)。很抱歉反应太晚。我这样做了,但是我不能在ngAfterViewInit()中使用originCity,因为getOriginCity(originCityForm:FormGroup)是map.html中的一个函数:
(ngSubmit)=“getOriginCity(originCityForm)
。我如何在ngAfterViewInit()中使用它?谢谢@Sergey Rudenko:)
  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();
  }