How to retrieve various data points from a service and pass them to a component in

Utilizing an httpmodule to fetch data from the backend, I am faced with a challenge. While loading data in the service and returning it to the component, I also need to send a status code along with it. Unfortunately, the Data model is already set and cannot be modified.

service

getData(offSet, maxResults): Observable<Data> {
    return this.http.get(this.url+"?offset="+offSet+"&maxResults="+maxResults);
}

component

this.dataService.getData(0, this.maxResults).subscribe((data)=>{
      this.data = data;
      this.total = data.totalCount;
      this.pages = Math.ceil(this.total / this.maxResults);
});

I want

In order to obtain the status code within the subscribe callback, my ideal scenario would look something like this:

this.dataService.getData(0, this.maxResults).subscribe((data, status_code)=>{
      this.data = data;
      this.total = data.totalCount;
      this.pages = Math.ceil(this.total / this.maxResults);
});

Answer №1

Angular's HttpClient normally only returns the request body. To access headers, status codes, and more, you need to include observe: 'response' in your HttpOptions.

This means that you will have to update your service accordingly.

  fetchData(offset, limit): Observable<{data: any, statusCode: number}> {
    return this.http.get(this.apiUrl+"?offset="+offset+"&limit="+limit, {observe: }).pipe(
      map((res: HttpResponse<any>) => {
        return {
          data: res.body,
          statusCode: res.status
        }
      });
    )
}

The updated code now returns an object with properties data and statusCode, allowing you to easily access them like this:

  this.dataService.fetchData(foo,bar).subscribe(res => {
    const { data, statusCode } = res;
    // do something...
  });

Answer №2

By including the option observe: 'response' in your HTTP request, you will receive a HttpResponse object instead of just the data. This object also includes the status code along with the response data.

Service:

retrieveData(offset, maxResults): Observable<HttpResponse<Data>> {
    return this.http.get(this.apiUrl+"?offset="+offset+"&maxResults="+maxResults, { observe: 'response' });
}

Component:

this.dataService.retrieveData(0, this.maxResults).subscribe((response)=>{
      this.data = response.body;
      this.totalItems = response.body.totalCount;
      this.pages = Math.ceil(this.totalItems / this.maxResults);
      // Access the status code using response.status
});

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

"Implementing a unique constraint in Drizzle-orm PostgreSQL with the additional condition of deleted_at being

Is there a way to construct a table using a WHEN SQL tag? I am interested in setting up a table similar to this: "members_table", { id: serial("id").primaryKey(), email: text("email").notNull(), team_id: text(&q ...

Revolutionize your Angular applications with dynamic template loading techniques

I recently developed a new component called componentB, which shares a similar template with another component, componentA. Currently, when a specific url is accessed, the original componentA is loaded. However, I want to load a slightly modified template ...

Exploring the world of Angular and utilizing TFS for seamless

Embarking on a new Angular development journey, I have relied on Angular documentation to guide me through the process - from installing node packages to creating a new Angular project. However, I am now looking to integrate my development work into an ex ...

Can optional parameters be used to restrict TypeScript overloads in any way?

My objective is as follows: interface ColorRgb { red: number; green: number; blue: number; } function rgbToHex(red: ColorRgb, green?: undefined, blue?: undefined): string function rgbToHex(red: number, green: number, blue: number): string function r ...

404 Error: The requested API endpoint seems to have gone missing, as the URL cannot be found

I encountered a 404 not found error when attempting to create a new customer in my angular 10 application. Oddly, the API method works flawlessly in Postman but fails when called from the angular client. The cause of this issue is eluding me Using Postman ...

The ngModelChange and change events are not activated when using md-select

Here is the code snippet I am working with: <md-select [(ngModel)]="model" (change)="updateModel()" (ngModelChange)="model=$event;updateModel()"> [...] <md-select> However, I am encountering an issue where when I update the model programmati ...

Intellij2016 is issuing warnings for the sass use of the :host selector in Angular2 code

One interesting feature of Angular 2 is the special selector it uses to reference its own component: :host display: block height: 100% !important width: 100% text-align: center position: relative However, Intellij does not provide a way to supp ...

What is the method for declaring constructor functions as object properties in TypeScript?

I am facing a challenge with typing an object that has a property which is a constructor function. How can I properly define the type for this situation: interface MyObj { constructor: () => ({ init: () => void }) } const myObj = { construct ...

Enable the parsing of special characters in Angular from a URL

Here is a URL with special characters: http://localhost:4200/auth/verify-checking/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="59663c34383035643230383d2b606a6e6b686d6e6e193e34383035773a3634">[email protected]</a> ...

Oops! Looks like there's a type error in module "*.mdx" - it seems that it doesn't have the exported member "metadata". Maybe try using "import metadata from "*.mdx"" instead?

I am attempting to extract metadata from an mdx file. I have followed the guidelines outlined in NextJS Markdown Frontmatter, but encountered build errors. It is important to note that I am unable to utilize fs. Code Section Page.tsx File import Conte ...

Trying to access @PreAuthorize with the role 'ROLE_ADMIN' is resulting in a Forbidden error

When restricting access to a method for only admins, one can make use of @PreAuthorize("hasRole('ROLE_ADMIN')"). Below is an example implementation: @CrossOrigin(origins="http://localhost:4200") @RestController @RequestMapping("/api/v1") public ...

Issue with deep linking functionality on S3 storage service turning out to be

After successfully deploying my angular5 app to: http://myApp.s3domain.amazonaws.com The Angular router is automatically directing me to http://myApp.s3domain.amazonaws.com/home However, when I try to access a link with a unique parameter like so: http:/ ...

Angular project seems to be stuck in a continuous cycle of

Currently, my application consists of spring boot as the backend and Angular as the front end. However, when I try to access the application through localhost:4200, the page continuously refreshes every few seconds. This issue did not occur previously, so ...

What is the process for eliminating the perplexing "default" attribute that has been inserted into JSON?

I recently came across the jsondata.json file: { "name": "John", "age": 30, "car": "ferrari" } Located in the same directory is a typescript file called main.ts where I simply output the json data using console.log import * as j from '. ...

Utilize ngrx/store to capture events from various components within an Angular application

Is there a way to utilize ngrx store in Angular to capture events from a grandchild component without relying on a service, Behavior Subject, or @Output? ...

The attribute 'custom' is not a recognized property on the type 'EventEmitter<any>'

Currently utilizing ionic 3, I have a part component alongside a parts page. Parts.html page: <ion-row> <part [part]="part"></part> </ion-row> The json structure for the part variable in parts.html is as follows: https://i.s ...

Is dynamic routing in Angular 8 only functional when utilizing RouterLink?

While working on dynamic routing in Angular, I ran into a strange issue. Dynamic routes only seem to be functional when accessed through a RouterLink, but the app crashes whenever I try to directly enter the URL in the browser. (The console error message ...

Translating SQL to Sequelize Syntax

I have an SQL query that I need to rewrite as a sequelize.js query in node.js. SELECT historyTable1.* FROM table1 historyTable1 WHERE NOT EXISTS ( SELECT * FROM table1 historyTable2 WHERE historyTable2.id=historyTable1.id AND historyTable2.da ...

I rely on Nebular for my Angular application, however, I am looking to make some manual CSS changes that I am having difficulty implementing

While using Nebular for my Angular app, I have run into issues with changing some CSS manually. Specifically, when using nb-select or nb-toggle, I am unable to customize the CSS as desired. Do you have any suggestions to help me with this problem? enter i ...

Challenges encountered while developing Angular FormArrays: Managing value changes, applying validators, and resolving checkbox deselection

I am facing an issue with my Angular formArray of checkboxes. In order to ensure that at least one checkbox is selected, I have implemented a validator. However, there are two problems that I need to address: Firstly, when the last checkbox is selecte ...