Sending information from service.ts to component

I'm encountering a roadblock with this issue, hopefully I can find some assistance here.

Essentially, I am attempting to make a simple get http request in http.service and then pass the json object to the filter.service. From there, I aim to transfer the output array to the component. However, I keep running into an empty error.

http.service

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/Rx';

@Injectable()
export class HttpService {

constructor(private http : Http) { }

getData() {
return this.http.get('https://angular2-49133.firebaseio.com/catalog.json')
       .map((response : Response) => response.json());
}

}

filtering.service

import { Injectable } from '@angular/core';
import { HttpService } from './http.service';

@Injectable()
export class FilterService {
public dataArr = [];
constructor(private httpService : HttpService) { }

setData() {
this.httpService.getData()
  .subscribe((data) => 
      {
        const resultArr = [];
        for(let key in data) {
          resultArr.push(data[key]);
        }
       this.dataArr = resultArr; //console.log(resultArr) works in component.
      }
  )
}

getData() {
return this.dataArr;
}

}

component.ts

import { Component, OnInit } from '@angular/core';

import { FilterService } from '../../filter.service';

@Component({
selector: 'ubi-item-section',
templateUrl: './item-section.component.html',
styleUrls: ['./item-section.component.css']
})
export class ItemSectionComponent implements OnInit{
items = [];
filter;
constructor(private filterService : FilterService) { }

ngOnInit() {
this.filterService.setData();
this.items = this.filterService.getData()

}
}

Answer №1

Consider returning a promise from the setData function once the this.dataArr object is populated.

Code Snippet

setData() {
  return new Promise(resolve, reject) {
    this.httpService.getData()
      .subscribe((data) => 
         {
            const resultArr = [];
            for(let key in data) {
              resultArr.push(data[key]);
            }
            this.dataArr = resultArr;
            resolve(this.dataArr); //resolve function will complete promise
         }
      );
   }
}

Wait for the completion of the AJAX call in the setData method by chaining a then block to the promise.

this.filterService.setData().then(
   () => this.items = this.filterService.getData()
);

Answer №2

Utilizing an asynchronous function called setData requires patience while waiting for the observable to resolve:

Give this a shot

filtering.service

import { Injectable } from '@angular/core';
import { HttpService } from './http.service';

@Injectable()
export class FilterService {
public dataArr = [];
constructor(private httpService : HttpService) { }

getData() {
return this.httpService.getData()
  .map((data) => 
      {
        const resultArr = [];
        for(let key in data) {
          resultArr.push(data[key]);
        }
       return resultArr; //console.log(resultArr) works in component.
      }
  )
}


}

component.ts :

import { Component, OnInit } from '@angular/core';

import { FilterService } from '../../filter.service';

@Component({
selector: 'ubi-item-section',
templateUrl: './item-section.component.html',
styleUrls: ['./item-section.component.css']
})
export class ItemSectionComponent implements OnInit{
items = [];
filter;
constructor(private filterService : FilterService) { }

ngOnInit() {
   this.filterService.getData().subscribe((items)=>{
      this.items = items;
   });
}
}

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

Is KeyValueDiffers within DoCheck limited to working with just a single object per component?

Initially, my ngDoCheck method worked perfectly with just this line: var productChanges = this.differ.diff(this.myProduct); Then I decided to add another object from my component and included the following line: var companyChanges = this.differ.diff(thi ...

Numerous unspecified generic arguments

Imagine a collection of functions, each capable of taking an argument and returning a value (the specifics don't matter): function convertToNumber(input: string): number { return parseInt(input) } function convertToBoolean(input: number): boolean { ...

Merging two arrays that have identical structures

I am working on a new feature that involves extracting blacklist terms from a JSON file using a service. @Injectable() export class BlacklistService { private readonly BLACKLIST_FOLDER = './assets/data/web-blacklist'; private readonly blackl ...

Upgrade your Angular 2 application by swapping out the Java socket client for the socket.io client

I have been successfully connecting to a server and sending a message using Java client socket. Now, I am attempting to achieve the same functionality using socket.io in my Angular 2 application. I have tried the code below but have had no success in sendi ...

The process of adding new files to an event's index

I'm trying to attach a file to an event like this: event.target.files[0]=newFile; The error I'm getting is "Failed to set an indexed property on 'FileList': Index property setter is not supported." Is there an alternative solution fo ...

Choose the "toolbar-title" located within the shadow root of ion-title using CSS

Within Ionic, the ion-title component contains its content wrapped in an additional div inside the shadow-dom. This particular div is designated with the class .toolbar-title. How can I target this div using a SCSS selector to modify its overflow behavior? ...

The mat-select element is defaulting to the last value in a loop for all dropdown selections

I am working with a Mat-select tag that is inside a loop using *ngFor, and by default, it is selecting the last value for all dropdowns. <div *ngFor="let investment of data.priorInvestmentExperiences; > <mat-form-field appearance="outline" ...

The Element is Unfamiliar - Application with Multiple Modules

I seem to be facing an issue with how my modules are structured, as I am unable to use shared components across different modules. Basically, I have a Core module and a Feature module. The Core module contains components that I want to share across multip ...

API rest data retrieval service in Angular

I'm currently working on my first Angular App and I need to fetch data from another local API Rest. My project is inspired by the Angular tutorial tour-of-heroes. I have created a component service to make API calls and display the results in another ...

Run a function from an alternate element

I have successfully created a grid with a button that enables me to control a timer. When I click on the start button in the grid on the home page, the timer begins counting the time. By using a service, I am able to determine whether the timer is active ...

Typescript is throwing a fit over namespaces

My development environment consists of node v6.8.0, TypeScript v2.0.3, gulp v3.9.1, and gulp-typescript v3.0.2. However, I encounter an error when building with gulp. Below is the code snippet that is causing the issue: /// <reference path="../_all.d. ...

The UploadFile Interface seems to be missing

Can someone clarify whether the @UploadedFile decorator's interface is predefined or if I need to define it myself? ...

Exploring the traversal of an array of objects within Tree Node

How can I transform my data into a specific Tree Node format? Is there a method (using Typescript or jQuery) to iterate through each object and its nested children, grandchildren, and so on, and modify the structure? Current data format { "content" ...

Jest tests reveal potential errors indicating an object may be null

When running my Jest (typescript) test cases on mongoose Models, I encounter numerous errors such as: Error TS2531: Object is possibly 'null'. For example, consider the following code snippet where the error is reported on line 3: const user = ...

How can I retrieve the SID received in a different tab using MSAL.js?

I have successfully integrated MSAL into a client-side library, and things are going smoothly so far. My next goal is to enable Single Sign-On (SSO) by following the instructions provided in the documentation at https://learn.microsoft.com/en-us/azure/act ...

Dealing with Angular 2's Http Map and Subscribe Problem

Looking to parse a JSON file and create a settingsProvider. This is how I am attempting it: import {Http} from "angular2/http"; import {Injectable} from "angular2/core"; @Injectable() export class SettingsProvider{ url: string = ""; constructor ...

Is there a way for me to store the current router in a state for later use

I am currently working on implementing conditional styling with 2 different headers. My goal is to save the current router page into a state. Here's my code snippet: const [page, setPage] = useState("black"); const data = { page, setPage, ...

Incorporating a JavaScript script into my Angular 7 project

My project requires me to incorporate the "Loadingbar.js" library into one of my pages. You can find this library here: . Initially, I inserted the CSS code into my global "style.css" file. I started by placing the script in my index.html file: <script ...

Assuming control value accessor - redirecting attention

import { Component, Input, forwardRef, OnChanges } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; @Component({ selector: 'formatted-currency-input', templateUrl: '../v ...

Router-outlet @input decorator experiencing issues with multiple components

Within my router module, I have a route set up for /dashboard. This route includes multiple components: a parent component and several child components. The data I am trying to pass (an array of objects called tablesPanorama) is being sent from the parent ...