Working with Angular 4: Utilizing HttpResponse in a Component

I am attempting to retrieve the response from my POST request using Angular 4. Below is the code I am using:

app.component.html:

`findAccordiSmall(pagination: Pagination) {
        this.accordiListTableLoading = true;
        debugger;
        this.accordiService.findAccordiSmall(pagination).subscribe(
          (res: HttpResponse<any>) => {
            res.headers.get('offset');
            res.headers.get('count');

            this.agreementList= res.body;

          }      errors => {
        this.accordiListTableLoading = false;
        Utils.notifyErrors(errors, this.notificationsService);
      }
    );

Service.ts

findAccordiSmall(pagination: Pagination): Observable<HttpResponse<any>> {

    const queryParams = this.getHttpParams(pagination).toString();

    return this.http.post(`${this.ENDPOINT}/agreements-paginated?${queryParams}`,pagination, { observe: 'response' })
        .catch(error => Utils.handleError(error, this.router, 'Errore nel recupero delle pratiche'));
}

The POST request is successfully retrieving all required data (headers, response, etc.), but I am facing difficulty in utilizing those values within my components. How can I access and utilize them? I need to populate: agreementList: Agreement[]; with the retrieved response.

Apologies for any confusion caused, please let me know if you require further information.

EDIT:This is the response I am receiving

Edit2:

Component.ts

  findAccordiSmall(pagination: Pagination) {
    this.accordiListTableLoading = true;
    this.accordiService.findAccordiSmall(pagination).subscribe(
      (res: Agreement[]) => {
        this.agreementList= res;
      },
  errors => {
    this.accordiListTableLoading = false;
    Utils.notifyErrors(errors, this.notificationsService);
  }
);

service.ts

 findAccordiSmall(pagination: Pagination): Observable<Agreement[]> {

        const queryParams = this.getHttpParams(pagination).toString();
        debugger;
        return this.http.post<Agreement[]>(`${this.ENDPOINT}/agreements-paginated?${queryParams}`,pagination, { observe: 'response' })
            .map(res => res)
            .catch(error => Utils.handleError(error, this.router, 'Errore nel recupero delle pratiche'));}

Answer №1

If you're looking to populate the agreementList: Agreement[] with a response, simply assign the value returned by a service function to it. There is no need to use res.body. Instead of this.agreementList= res.body;, you should use this.agreementList = res;

UPDATE: Revised component code:

findAccordiSmall(pagination: Pagination) {
    this.accordiListTableLoading = true;
    debugger;
    this.accordiService.findAccordiSmall(pagination).subscribe(
      (res: Agreement[]) => {
        this.accordiListTableLoading = false;
        this.agreementList= res;
      },
  errors => {
    this.accordiListTableLoading = false;
    Utils.notifyErrors(errors, this.notificationsService);
  }
);

I have corrected your service function to return the proper value, and you also need to apply a map operation.

findAccordiSmall(pagination: Pagination): Observable<Agreement[]> {

const queryParams = this.getHttpParams(pagination).toString();

return this.http.post<Agreement[]>(`${this.ENDPOINT}/agreements-paginated?${queryParams}`,pagination, { observe: 'response' })
    .map(res => res)
    .catch(error => Utils.handleError(error, this.router, 'Error retrieving agreements'));

}

Now the function returns Observable<Agreement[]>, which means that when you subscribe to it, the res inside the subscribe will be extracted from an Observable and its type will be Agreement[]

subscribe((res: Agreement[]) => {})

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

How can I call a method from a class using Typescript when getting an error saying that the property does not exist on the

Below is a service definition: export class MyService { doSomething(callbacks: { onSuccess: (data: Object) => any, onError: (err: any) => any }) { // Function performs an action } } This service is utilized in a component as shown be ...

Creating encoded objects for a content-type of `application/x-www-form-urlencoded`

Upgrading AngularJS Code to Angular 2+ - Http Issue I am in the process of converting some legacy AngularJS code (specifically Ionic 1) to the latest version of Angular (Ionic 4), and I've encountered a troubling issue. Previously, in every HTTP POS ...

Angular application triggering multiple subscribe method calls upon a link click event

Here is the code for my navbar component: <li *ngFor="let item of menu"> <a *ngSwitchCase="'link'" routerLinkActive="active" [routerLink]="item.routerLink" (click)="Navigation(item.title)&q ...

Unable to define the type for the style root in Typescript

I am encountering an error that is asking me to code the following types in the root tag: No overload matches this call. Overload 1 of 2, '(style: Styles<Theme, {}, "root">, options?: Pick<WithStylesOptions<Theme>, "fli ...

Unable to access the values of the object within the form

I am encountering an issue where I cannot retrieve object values in the form for editing/updating. The specific error message is as follows: ERROR TypeError: Cannot read properties of undefined (reading 'productName') at UpdateProductComponen ...

My current setup includes Node.js version 8.11.2 and Angular CLI version 7.1.2. However, upon running Angular CLI 8.0+, it displays an error stating "You are running version v8.11.2 of Node.js, which is not supported

From the beginning of my project, I encountered a version error which led me to uninstall and delete all Node and CLI files before reinstalling them. However, now when I try to run npm start, I am faced with the following message: The current Node.js vers ...

Set up the user django with standard configuration values

I'm currently working with Django and Angular 2, trying to create a user with default values, but it's not happening as expected... Model class Settings(models.Model): user = models.ForeignKey('auth.User', related_name='setti ...

Executing Karma tests in IntelliJ with Angular 6

After upgrading my angular application from version 5.2 to version 6, everything seems to be working smoothly. However, I encountered an error while trying to run a test from IntelliJ: Error: The '@angular-devkit/build-angular/plugins/karma' ka ...

Encountered Typescript errors TS1110 and TS1005

Error in TypeScript: typings/node/node.d.ts(83,23): Type expected. TypeScript issue: typings/node/node.d.ts(1830,52): Expected '=' sign. My TypeScript compilation is failing at node.d.ts, despite multiple attempts to reinstall it. ...

Is it better to convert fields extracted from a JSON string to Date objects or moment.js instances when using Angular and moment.js together?

When working on editing a user profile, the API call returns the following data structure: export class User { username: string; email: string; creationTime: Date; birthDate: Date; } For validating and manipulating the birthDate val ...

What is the importance of maintaining immutability for objects in Redux?

What is the importance of immutability in Redux? While I understand that frameworks like Angular2 use onPush to leverage immutability for quicker rendering of views, I'm interested in learning about other reasons why Redux emphasizes immutability desp ...

Why can't Angular iterate through objects using ngFor in Typescript?

Here's what I currently have: public posts: QueryRef<PostsInterface>; this.posts = this._postService.get(); //in ngOnInit In my HTML file, it looks like this: <mat-card *ngFor="let post of posts | async"> This allows me to display eac ...

The Angular 5 keyup event is being triggered twice

My app is incredibly simple, just a basic hello world. To enhance its appearance, I incorporated bootstrap for the design and ng-bootstrap for the components. Within one of my TS files, you will find the following code: showMeTheKey(event: KeyboardEvent) ...

Using @emotion/styled alongside esbuild has caused an issue where importing styled11 as default.div is not functioning as expected

Working on building a website using esbuild, react, and emotion/MUI has been smooth sailing so far. However, I've hit a roadblock with getting the styled component from @emotion/styled to function properly. uncaught TypeError: import_styled11.default ...

Contrasting characteristics of class members in JavaScript versus TypeScript

Typescript, a superset of Javascript, requires that Javascript code must function in Typescript. However, when attempting to create class members in a typescript file using the same approach as Javascript, an error is encountered. CODE :- script.ts (types ...

Angular: Utilizing Parameters in HTTP GET Requests

I've recently started using Angular. Currently, I'm working on sending a parameter in an HTTP GET request. This is what my code looks like: for (var i = 0, len = this.recentArtists.topartists.artist.length; i < len && i < h ...

Potential keys + keys that are present in the `initialData`

Is there a way to specify the type of data in order to include all keys that exist in initialData plus additional keys from Item as Partial(optional)? class TrackedInstance<Item extends Record<string, any>, InitialData extends Partial<Item> ...

What could be causing the undefined properties of my input variables in Angular?

Currently, I am fetching data from a service within the app component and passing it down to a child component using @Input. Oddly enough, when I log the data in ngOnInit, it appears correctly in the child component. However, when I try to assign it to a v ...

Using Angular and Spring to Add Captcha to Your Web Application

Is there a way to incorporate captcha into an Angular application with Java-Spring Boot as the backend without using Google's reCaptcha library? The server hosting the application does not have Internet access. At the moment, I am sending a captcha n ...

I am encountering a PeerInvalid error when attempting to launch myapp on an Android device using Ionic/Angular 4

For the past 3 days, I've been using Ionic and today I decided to try putting my application on my Android devices. However, I've encountered a problem... When I run: ionic cordova run android --device -l -debug I'm getting these errors th ...