How to retrieve the HTTPClient value in Angular?

APIservice.ts

public fetchData(owner: any) {
    return this.http.get(`${this.url}/${owner}`, this.httpOptions).pipe(
      catchError(e => {
        throw new Error(e);
      })
    );
  }


public fetchDataById(id: number, byId:string, owner: any) {
    return this.fetchData(owner).subscribe(data => {
      Object.keys(data).map(function(key) {
        return data[key].filter(x => x[byId] === id);
      });
    })

station.service.ts

getStationsByOrganizationID(id) {
    return this.APIservice.fetchDataById(id, 'orgId', 'station');
  }

managestation.component.ts

getStationsByOrgID(id) {
    this.sta = this.stationService.getStationsByOrganizationID(id);
  }

managestation.component.html

<ion-content class="body">
  <ion-button expand="block" (click)="onAddStation()">Add Station
    <ion-icon name='add' slot="end"></ion-icon>
  </ion-button>
  <ion-list>
    <ion-item *ngFor="let s of sta">
      <ion-label>{{ s.name }}</ion-label>
      <ion-label>{{ s.orgId }}</ion-label>
      <ion-icon name='create' slot="end" (click)="onEditStation(s.id)"></ion-icon>
      <ion-icon name='trash' slot="end" (click)="onDeleteStation(s.id)"></ion-icon>
    </ion-item>
  </ion-list>
</ion-content>

Error

ERROR Error: "[object Object]" Angular 11 core.js:4002

How do I retrieve the values of fetchDataById in managestation.component.ts and set it to this.sta?

Answer №1

Adjust your files as directed below

data-service.service.ts

public fetchDataById(id: number, byId:string, owner: any) {
    return new Promise((resolve, reject) => {
     this.fetchData(owner)
      .subscribe(data => {
        let filteredData = Object.keys(data).map(function(key) {
         return data[key].filter(x => x[byId] === id);
        });
        resolve(filteredData);
      })
    });
}

managestation.component.ts

retrieveStationsByOrganization(id) {
    this.stationService.getStationsByOrg(id)
    .then((allData) => {
       this.stations = allData;
    })

  }

Answer №2

When it comes to returning subscriptions, here are a couple of options:

  • Option 1: Return the observable itself
    public httpGetAllBy(id: number, byId:string, owner: any) {
        return this.httpGetAll(owner);
    }
    
    getStationsByOrg(id) {
        return this.dataSharing.httpGetAllBy(id, 'orgId', 'station').subscribe(data=>{
          const newData = Object.keys(data).map(function(key) {
            return data[key].filter(x => x[byId] === id);
          });
    //implement your logic in station.service.ts
    };
    
    Option 2: Utilize async/await for fetching data
    public async httpGetAllBy(id: number, byId:string, owner: any) {
        return await this.httpGetAll(owner).toPromise().then(data => {
          return Object.keys(data).map(function(key) {
            return data[key].filter(x => x[byId] === id);
          });
        })
        
    getStationsByOrg(id) {
        return this.dataSharing.httpGetAllBy(id, 'orgId', 'station').then(data=>{
    //implement your logic in station.service.ts
    };
    

Answer №3

To enhance your service functionality, it is advisable to use Observables and apply mapping through the pipe method.

public fetchAllItemsBy(id: number, byId:string, owner: any) {
    return this.fetchAllItems(owner).pipe(
        map( (data => {
            Object.keys(data).map(function(key) {
                return data[key].filter(x => x[byId] === id);
            });
        }))
    );
}

You can then subscribe to this in your component for further processing.

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

Activate the mat-select selectionChange trigger when making changes to the form via patchValue

I have been working with an angular reactive form that includes a mat-select element with a selectionChange event. After updating the form using patchValue, I noticed that the selectionChange event does not trigger. I'm unsure how to proceed and woul ...

Building applications for platform iOS is not supported on this operating system

I'm currently exploring the features of NativeScript + Angular + SQLite for building a mobile application, and I am referencing this video as a guide. However, when I reached the 3:00 mark, it instructed me to execute the command tns platform add ios ...

Utilize React to transform PDF files into PNG images and seamlessly upload them to Cloudinary

Currently, I am utilizing react typescript and looking to select a PDF file, transform the PDF into an image, and then upload the final image onto Cloudinary. Although I have a service set up for uploading images in my Cloudinary media library, I am unsu ...

The marker is not updating in real-time with the actual latitude and longitude on the Google Maps angular

I have been attempting to update the marker in my Angular Google Map in real-time, but unfortunately it is not working as expected. It only displays the initial static data and then fails to update. Despite conducting a thorough search on Google, I have be ...

Angular, perplexed by the output displayed in the console

I'm completely new to Angular and feeling a bit lost when it comes to the console output of an Angular app. Let me show you what I've been working on so far! app.component.ts import { Component } from '@angular/core'; @Component({ ...

Issues with React Material UI Select functionality not performing as expected

I've been working on populating a Select Component from the Material UI library in React, but I'm facing an issue where I can't choose any of the options once they are populated. Below is my code snippet: import React, { useState, useEffect ...

Encountered an issue while trying to access a property that is undefined in the

How can I extract data from a dropdown menu and display it in a text box? For instance, if a user selects an ID from the dropdown, I want to show the corresponding name in the textbox. I hope this explanation is clear and properly conveyed, as my English s ...

Adding extra information to a property or array in Firebase

The following code snippet demonstrates how to create an array of event objects using observables. eventsRef: AngularFireList<any>; events: Observable<any>; this.eventsRef = db.list('events'); this.events = this.eventsRef.snapshotC ...

The debounced function in a React component not triggering as expected

I am facing an issue with the following React component. Even though the raiseCriteriaChange method is being called, it seems that the line this.props.onCriteriaChange(this.state.criteria) is never reached. Do you have any insights into why this.props.onC ...

Adding FormControl dynamically to FormGroup can be achieved by simply using the appropriate method

Currently, I am working with a plunker where I am dynamically creating form components based on the model specified in app.ts. However, I am facing an issue where I cannot add formControlName = "name" to the component. In my control-factory.directive.ts ...

Introducing the Angular 2/4 Dashboard Widget Module!

I am currently developing the dashboard for my Angular 2 application and I am in search of an npm package that fits my requirements. I came across a link that provides similar functionalities to what I need, which is . I want to be able to add new w ...

Issue with dependency injection in Angular 16 when used as a standalone feature

Here are my standalone API calls within the service: import { Injectable} from '@angular/core'; import { ProductEndPoints } from '../../constants/apiConstants/product-endpoints'; import { HttpClient} from '@angular/common/http&ap ...

Unresolved (waiting for response) unidentified

I encountered a perplexing error in Chrome and I am unable to identify its source: https://i.sstatic.net/f9Blt.png The only clue I have is that after refactoring approximately 10,000 lines of code, this error surfaced. It occurred during the middle of the ...

Error encountered while running `ionic build android`. To view the stack trace, try running the command with the `--stacktrace` option

I've gone ahead and installed the sdk, as well as added JAVA_HOME, so why am I encountering this error when executing ionic build android? It seems that you haven't accepted the license agreements for certain SDK components: [Android SDK Platf ...

The Angular text is not separating the rows with space

Hello, I am a beginner with Angular. Recently, I encountered an issue in my Angular App where the rows of text are not properly spaced out as I intended. Ideally, I would like them to form a list like this: - ingredient - ingredient - ingredient However ...

Determine to which observable in the list the error corresponds

const obs1$ = this.service.getAllItems(); const obs2$ = this.service.getItemById(1); combineLatest([obs1$, obs2$]) .subscribe(pair => { const items = pair[0]; const item = pair[1]; // perform actions }, err => { // det ...

Exploring the various methods of setting up a Create React App project with TypeScript

One of my old books from a year ago mentioned... npx create-react-app XXX --typescript But looking at the current Create React App documentation, it says... npx create-react-app XXX --template typescript They both seem to yield the same result. Is ther ...

A step-by-step guide on integrating Detox with jest (ts-jest) and Typescript in a react-native app

I've been experimenting with incorporating Typescript into my detox tests. The most relevant information I could find was in this gist. However, when trying to implement it, I encountered an error stating that jasmine is not defined. After researching ...

Utilizing Angular's intelligent dichotomy of (container) and (presentational) components, integrating conditional logic, and effectively passing inputs throughout the

Imagine you have two simple components, A and B. Component C will only display either component A OR B, which is controlled by smart component D. D (smart) | C (simple) / \ A B (both simple) Both components A and B have 10 inputs each. Ther ...

What is the reason behind typescript making it necessary for me to find a way to set a value of type

function f1() { const v : string = String(); if(v) {alert("IF");} // OK const b : boolean = v; // Type 'string' is not assignable to type 'boolean'. if(b) {alert("BOOLEAN");} } f1(); My approach to this issue involv ...