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

I prefer not to run the next.js SWR until after the initial rendering

Development Setup ・ next.js ・ typescript ・ swr This uses swr for communication purposes. I am looking to only trigger it when the query value changes. However, it is also being executed during the initial rendering. How can I prevent it ...

What is the process for importing a JSON5 file in Typescript, just like you would with a regular JSON file?

I am looking to import a JSON5 file into a JavaScript object similar to how one can import a JSON file using [import config from '../config.json']. When hovering over, this message is displayed but it's clearly visible. Cannot find module & ...

Utilize a single component across various instances for enhanced efficiency

After thorough research, I couldn't find a solution to my problem despite similar questions being asked. I've developed an angular component for styled radio buttons and need to use it multiple times on different instances. To get a better unde ...

Angular component linked to a dynamic object requiring user confirmation before changing or reverting to the original value

I've been working on getting a simple <select> behavior where the value reverts back if the user cancels the change. I managed to achieve it, but it took me quite a few hours and I'm not entirely satisfied with the implementation as it&apos ...

Changing the type of an object's property in TypeScript on the fly

I am working on a TypeScript function that is designed to dynamically modify the property of an object. Here is the function: const updateProperty = (value: any, key: keyof Type1, obj: Type1) => { obj[key] = value; } Below is the definition of "Typ ...

Is it recommended for TypeScript to automatically resolve the index.ts file as the default module file?

Struggling with getting the module resolution to work in TypeScript. Consider the following file structure: /modulename/index.ts Should it be resolved like this? import * as modulename from "modulename" I can't seem to make it work. However, imp ...

Comparing Angular 2 Components and AngularJS Directives: What Sets

Are there any parallels or distinctions between an angular2 component and an AngularJS directive? It seems that these two share similar functionalities in the angular2 component and AngularJS directive. Additionally, angular2 also incorporates a directive ...

How do I implement branch code using TypeScript types in Svelte?

Looking for a solution similar to the one mentioned in Typescript: How to branch based on type, but tailored for Svelte. Despite implementing run-time type guards as suggested, Svelte continues to throw errors. I am dealing with an array called collectabl ...

Is there a way to create a new perspective for Ion-Popover?

Looking for a solution: <ion-grid *ngIf="headerService.showSearch()"> <ion-row id="searchbar" class="main-searchbar ion-align-items-center"> <ion-col size="11"> ...

Automatic Form Saving in Angular 4

Seeking to create a form data autosave feature in Angular 4. The functionality should operate as follows: User modifies data in the form -> save request sent to DB. A timer is initiated for 2 seconds. During the 2-second window after the previous save ...

Transforming functions into a new typed object with different function signatures

I am currently updating some React/Redux code that previously followed an older pattern to a more modern "hooks" based approach, using TypeScript. In the old pattern, we utilized "class-based" components and passed their "dispatch" functions using mapDisp ...

Upgrading to Angular 14 has caused issues with component testing that involves injecting MAT_DIALOG_DATA

After upgrading Angular from 14.1.1 to 14.2.10 and Material from 14.1.1 to 14.2.7, a peculiar issue arose when running tests with the default Karma runner. I am at a loss as to what could have caused this problem, so any advice would be appreciated. The u ...

The situation I find myself in frequently is that the Angular component Input

There seems to be an issue with a specific part of my application where the inputs are not binding correctly. The component in question is: @Component({ selector : 'default-actions', templateUrl : './default.actions.template.html&a ...

Exploiting CORS in Angularjs IONIC

I am making use of the $http.post() function to call an API, but unfortunately, I am encountering a problem with the response. There seems to be an issue with the XMLHttpRequest as it fails to load . The preflight response does not allow the Content-Type ...

Exploring data retrieval from nested arrays of objects in TypeScript/Angular

I have an API that returns an object array like the example below. How can I access the nested array of objects within the JSON data to find the role with roleid = 2 when EmpId is 102 using TypeScript? 0- { EmpId: 101, EmpName:'abc' Role : ...

Is there a way to automatically select all checkboxes when I select contacts in my case using Ionic 2?

initializeSelection() { for (var i = 0; i < this.groupedContacts.length; i++) { for(var j = 0; j < this.groupedContacts[i].length; j++) this.groupedContacts[i][j].selected = this.selectedAll; } } evaluateSelectionStatus() { ...

Removing sourceMappingURL from an Angular Universal build: A step-by-step guide

Using this repository as my foundation, I have successfully resolved most of the plugin errors except for one that continues to elude me. It's puzzling because no other plugin anticipates a .map file in an SSR build since it is intended for productio ...

The function RegisterOnChange is not a valid function

I utilized FormBuilder(fb) to create this form. this.serviceRecordForm = this.fb.group({ client: [], serviceRecordItem: this.fb.group({ productStatus: [''], password: [''], hasBackup: ...

Is there a way to access the Angular directive instance from the console?

ng.probe($0).componentInstance allows you to access the reference to the instance. Can we retrieve the directive instance from the console in any way? ...

Transform array of elements from type T1 to element in the array to type T2

Here is a Typescript class I am working with: export class Envelope<T> { result: T; constructor(result: T) { this.result = result; } } I'm trying to convert Envelope<RecentPostResponse[]> to Observable<PostModel[]>: getP ...