I'm looking to retrieve the Response from a POST request, which happens to be an array of SearchSample objects in Angular

My Component's Search Function:

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

My Service's Search Function:

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

The Result in the Console :

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

I WANT TO EXTRACT THE VALUES OF sampleId and distance

Answer №1

To retrieve the response content, utilize a map operator.

For example:

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

This will display the array of samples.

If you only need to access one variable from the first item in the array, you can do so like this:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the process of Angular initializing applications and generating DOM elements

Imagine a scenario where there is a button: <button (click)="clicked()" class="but">Click2</button> Accompanied by a component: export class AppComponent { but = document.querySelector('.but'); clicked(){ console.lo ...

Differences between Arrays of Numbers and Objects in Typegoose

Exploring Typegoose and encountering a puzzling issue. I defined a class with a field meant to store an array of numbers like this: class A { ... some other properties ... @prop({ required: true }) public nums!: number[]; } Here's a snippet of ...

Navigating through embedded arrays in Angular

JSON Object const users = [{ "name":"Mark", "age":30, "isActive" : true, "cars":{ Owned : ["Ford", "BMW", "Fiat"], Rented : ["Ford", "BMW", "Fiat" ...

Filtering an array of objects based on another array of objects in Angular2 through the use of pipes

I'm having trouble understanding how to use the angular pipe to filter an array of objects based on another array of objects. Currently, I have a pipe that filters based on a single argument. I am working with two arrays, array1 and array2, both cont ...

Issue with demonstrating the Material Angular expansion-panel feature

Exploring the world of Material Angular has been an exciting journey. Recently, I've been experimenting with adding components to my project. Currently, I'm focused on incorporating the expansion-panel component example into a dialog. However, de ...

Unable to implement new ecmascript decorators within typescript version 2.4.2

Check out this example code: function enumerable(value: boolean) { return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) { descriptor.enumerable = value; }; } class A { @enumerable(false) a: number = 1 b: number ...

Combine various HTTP requests in Angular using RxJS, ensuring that the outer request is emitted immediately

I'm struggling to fully understand some aspects of RxJS operators. Below is some code snippet from a component: extendedOrders$ = this.salesService.getOrders().pipe( switchMap(orders => { return forkJoin(orders.map(order => { return ...

Ways to shift the focus away from the current date in the Angular Material Datepicker

Is there a way to prevent the focus on today's date when utilizing Angular Material datepicker? I have attempted to include certain properties to mat-datepicker without success. Here is what I have tried: restoreFocus="false" [startAt]="null" &l ...

The ng-bootstrap modal fails to appear when incorporating [formGroup]="FormName" or formControlName="elementName"

Utilizing ng-bootstrap to create a popup modal has been a challenge for me. When I import FormsModule and ReactiveFormsModule in src/app/modal-basic.module.ts, the code inside it looks like this: import { NgModule } from '@angular/core'; import { ...

Is it possible to access the generic type that a different generic type inherits in TypeScript?

I've developed an interface specifically designed for types capable of self-converting to IDBKey: interface IDBValidKeyConvertible<TConvertedDBValidKey extends IDBValidKey> { convertToIDBValidKey: () => TConvertedDBValidKey; } My goal n ...

Encountering an undeclared variable when trying to access associative arrays in PHP

In my case, I have two arrays that I am working with - "OperID" and "OperSums". The "OperID" array consists of ID numbers while the "OperSums" array consists of IDs linked to corresponding totals. Here is a glimpse of how these arrays look: Array 1 {[0] ...

Unit testing Firebase function with Jest for mocking

Currently, I am in the process of developing unit tests and facing challenges with mocking Firebase functions while specifying the return type upon calling them. The code snippet below illustrates what I intend to mock (account.service.ts) and provides ins ...

The directive within the module was not carried out

After setting up a fresh module in my Angular 8 project and adding a new directive to it, nothing seemed to happen at runtime (although the compilation was successful). I even added console logs to the directive to check if it was being executed different ...

Exploring the Values in an Array Using PHP

As someone who is new to Php, I have an array that looks like this: Array ( [0] => {"tranc":["2"],"report":["2"],"company":["2"],"facilities":["2"],"area": ...

Experimenting with the routerLink directive in Angular 2

Currently, I am in the process of testing routing functionality. As part of this, I have moved my navbar to a separate component called MdNavbar, which primarily consists of HTML and CSS. The RouteConfig is located in another component where MdNavbar is in ...

Is there a way to access a specific argument in yargs using typescript?

The idea behind using yargs is quite appealing. const argv = yargs.options({ env: { alias: 'e', choices: ['dev', 'prod'] as const, demandOption: true, description: 'app environment&apos ...

Managing JSON error responses in Blob HTTP requests

One common scenario involves making HTTP calls like the following: this.http.get(`${environment.baseUrl}/api/v.1/reports/...`, { responseType: ResponseContentType.Blob }) This call returns PDF files as blobs, which we then save using FileSaver. The iss ...

Tips on implementing computed properties in Vue.js while using TypeScript

There is a significant amount of documentation on how to utilize Vue.js with JavaScript, but very little information on using TypeScript. The question arises: how do you create computed properties in a vue component when working with TypeScript? According ...

In any project, the functionality of *ngFor in Ionic 4 seems to be malfunctioning

Embarking on my journey with Ionic and Angular, I am faced with a straightforward task: displaying received data within an ion-card. To achieve this, I have set up an "ActivityService" to manage the data. Here is my app.module.ts: import { NgModule } from ...

Angular2 with Electron is a stellar demonstration of a successful integration

I'm interested in exploring Electron with Angular2 and I'm on the lookout for a reliable example on GitHub that combines these technologies. Ideally, I would like to find a repository that I can easily download as a zip file, run npm install, npm ...