【问题标题】:i need to access a POST request Response and that Response is An array of SearchSample objects Angular我需要访问一个 POST 请求响应,该响应是一个 SearchSample 对象数组 Angular
【发布时间】:2022-08-10 11:36:46
【问题描述】:

我的组件中的功能:

searchWithNyckel(){

const formData = new FormData();
formData.append(\'image\', this.updateFormGroup.get(\'updateProduct.image\').value);

this.productService.searchProductNyckel(formData).subscribe(
  data => {
    this.resForSearch= data
    console.log(JSON.stringify(this.resForSearch));
    // this.resForSearch.values()
  }
)
}

我的服务中的功能:

searchProductNyckel(formData: FormData):Observable<SearchRes[]> {
    const url = `https://www.nyckel.com/v0.9/functions/1wx5f2474e1ntc/search`
    return this.httpClient.post<SearchRes[]>(url,formData);
  }

控制台响应:

{
\"searchSamples\": 
    [{
        \"sampleId\": \"<sampleId>\",
        \"distance\": 0.86,
        \"externalId\": \"<externalId>\"
    }]
}

我需要得到 sampleId 和 distance 的值

    标签: arrays angular typescript nyckel


    【解决方案1】:

    您可以使用 map 运算符访问响应的内容。

    例如:

    this.productService.searchProductNyckel(formData).pipe(
       map (response => response.searchSamples)
    ).subscribe((samples => console.log(sample))
    
    

    将输出样本数组。

    如果您只想访问数组第一项的 1 个变量,您可以使用:

    this.productService.searchProductNyckel(formData).pipe(
       map (response => response.searchSamples[0].sampleId)
    ).subscribe((id => console.log(id))
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-12
      • 1970-01-01
      • 1970-01-01
      • 2022-10-24
      • 2012-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多