The Angular service uses httpClient to fetch CSV data and then passes the data to the component in JSON format

I'm currently working on an Angular project where I am building a service to fetch CSV data from an API server and convert it to JSON before passing it to the component.

Although the JSON data is successfully logged in the console by the service, the component displays a much earlier message saying Component data: UNKNOWN.

To achieve the conversion of CSV to JSON, I am utilizing the csvtojson module.

Below is the code snippet for the Component part:

  getData(): any {
    this.storeService.getData()
      .subscribe(data => {
        console.log('Component data: ', data);
      }, error => {
        console.log(error);
      });
  }

Here's the code for the "storeService" service:

  getData(): Observable<any> {
    return this.httpClient
      .get('http://localhost:3000/user/11', { responseType: 'text' as 'text' })
      .pipe(
        map((data) => {
          csv({
            noheader: true,
            trim: true,
            delimiter: ';'
          })
            .fromString(data)
            .then(jsonData => {
              // Successfully logging JSON data in the service
              console.log('Service jsonData', jsonData);
              // How can I pass this jsonData to the component?
              return jsonData;
            })
        })
      )
  }

Your assistance would be greatly appreciated. Thank you.

Answer №1

To address this issue, a simple solution is to utilize a behaviorSubject where the retrieved data can be stored. Subsequently, accessing the data in your component.ts file involves subscribing to the behaviorSubject.

After subscribing, you can easily retrieve the updated value by invoking this.storeService.getData(); (as the component will automatically update upon any changes since it subscribed to the behaviorSubject).

Modify your "storeService" as shown below:

yourJsonData: BehaviorSubject<any> = new BehaviorSubject<any>(null);

 getData(): Observable<any> {
 // DO NOT RETURN HERE
    this.httpClient
      .get('http://llocalhost:3000/user/11', { responseType: 'text' as 'text' })
      .pipe(
        map((data) => {
          csv({
            noheader: true,
            trim: true,
            delimiter: ';'
          })
            .fromString(data)
            .then(jsonData => {
              // Here we have a JSON data
              console.log('Service jsonData', jsonData);
              // STORE THIS JSONDATA TO A BEHAVIOUR SUBJECT
              this.yourJsonData = jsonData;
            })
        })
      )
  }

Update your Component.ts file with the following code:

   getData(): any {
    this.storeService.getData();
    
    this.storeServiceVariable.yourJsonData.subscribe((data) => {
      console.log('Component data: ', data);
    });   
  }

Answer №2

Consider Implementing:

Simply retrieve the data within the service and manipulate it in the component as shown below

Service.ts

fetchData(): Observable<any> {
    return this.httpClient
      .get('http://localhost:3000/user/11', { responseType: 'text' as 'text' });
}

Component.ts

retrieveData(): any {
    this.dataService.fetchData()
      .subscribe(response => {
        csv({
            noheader: true,
            trim: true,
            delimiter: ';'
        }).fromString(response).then(parsedData => {
             // JSON data is visible here
             console.log('Parsed Data from Service:', parsedData);
        });
      }, error => {
        console.log(error);
      });
  }

This should provide some assistance....

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

Verify the presence of a boolean false value in mustache.js

As stated in this particular query, the method of checking for false within a json object passed to a mustache template is as follows: {{^like}} it is false {{/like}} {{#like}} it is true {{/like}} Assuming our json data appears like this {"like" ...

Avoiding Maximum Call Stack Size Exceeded in Observables: Tips and Tricks

After filtering, I have a list stored in the variable filteredEvents$: public filteredEvents$ = new BehaviorSubject([]); I also have a method that toggles the checked_export property and updates the list: public checkAll(): void { this.filteredEve ...

Display a browser alert in Angular 5 whenever a query parameter undergoes modification

In my web application, there is a Parent component called Item which has the route '/Item'. Within this Parent component, I have two children components: one is named Catalogue and the other is named AddSize. By default, when the page loads, th ...

Utilizing MSAL's loginRedirect within an Ngrx Effect: A step-by-step guide

Is there a way to utilize Msal angular's loginRedirect(): void function instead of loginPopup(): Promise in an Ngrx Effect? I've been able to successfully implement the loginPopup() method, but since loginRedirect() has a void return type, it di ...

Deciphering complex JSON structures in PHP

I've come across a JSON structure that I need to parse. While I have managed to extract individual nested objects, it feels like there should be a simpler way to achieve this without having to search for each nested structure. Here is an example of t ...

Asynchronous data binding in Angular 2

I'm trying to pass a value from my ImageDetail component to the ImageComment component as follows: ImageDetailHtml: <image-comment [photo]="photo"></image-comment> ImageCommentComponent: export class ImageCommentComponent { @Input(&a ...

What is the process for defining child routes in Angular 2.0 for Dart?

When working with TypeScript, a child route can be easily defined as shown below: export const routes: Routes = [ { path: '', redirectTo: 'product-list', pathMatch: 'full' }, { path: 'product-list', component: P ...

Implementing onClick functionality in RecyclerView post JSON data extraction

I recently implemented a RecyclerView in a fragment and successfully parsed JSON data from a website to display it in the RecyclerView following a helpful tutorial found at: Now, my next challenge is adding an onClick listener to the items in the Recycler ...

Angular 7 SPA encountering Media Type Not Supported 415 issue when communicating with .NET, despite successful request in Postman

My SPA is encountering a 415 Unsupported Media Type Error when it calls a specific endpoint in my .NET API that I recently implemented pagination for. Interestingly, the same call from Postman is successful without any errors. It's puzzling why the id ...

Transforming flat JSON into nested JSON with multiple arrays can be achieved using the Jolt transform

Struggling to create a JOLT transformation for converting flat JSON to nested JSON? Need help transforming the JSON structure using a JOLT spec? Visit to test your transformations. Input : [ { "container_id": "a", "carr ...

Encoding URLs in Angular 2 for HTTP POST requests

I am attempting to utilize a service through post with Angular2. Below is my code snippet: var m_dataRequest = this.buildLoginUserPasswordRequest(password, key); let headers = new Headers({ 'Accept': '*/*', &apos ...

Tips for arranging backend data horizontally within Bootstrap horizontal cards

After setting up my Angular application, I created a dashboard page and made API calls for dynamic signals (signal-1, signal-2, etc). To showcase this data, I decided to use Bootstrap horizontal cards. However, I'm facing an issue with displaying the ...

Revamp label titles in Ionic/Angular by incorporating a hyperlink for updating the image

Seeking guidance on changing labels in an Ionic/Angular app from 0, 1, 2 to Profile, Group, and Friend. Despite utilizing resources like Google and YouTube, I've struggled for days to make this adjustment without success. Any assistance would be great ...

Converting a list of base classes to JSON using Unity's JSONUtility

I am working with a BaseClass and several subclasses. In my code, I have a List<BaseClass> that holds instances of these subclasses. When I try to convert this list to JSON using JSONUtility.ToJson(List<BaseClass>), it only includes propertie ...

Angular 4 allows for dynamically applying the active class to a clicked button, enhancing interactivity

Issue: <button *ngFor="let button of buttons" [ngClass]="{'active': isClicked}" (click)="isClicked = !isClicked" Description: A total of 10 buttons are displayed on the screen. When I click on button number 1, each button receives the clas ...

"Failure encountered while trying to fetch JSON with an AJAX request

I am facing an issue with an ajax request. When I make the request with the property dataType: 'json', I get a parsererror in response. My PHP function returns the data using json_encode(), can someone assist me? On the other hand, when I make th ...

Implement video.js within an Angular 2 application

I've been attempting to use video.js for my angular2 videos, but I've hit a roadblock. I have included the video.js CDN in my index file. <link href="https://vjs.zencdn.net/5.11/video-js.min.css" rel="stylesheet"> <script src="https://v ...

Converting personal injury claims into configuration maps with the help of jq

Here is my input: { "apiVersion": "apps/v1", "kind": "Deployment", "spec": { "template": { "spec": { "containers": [ { "volum ...

Angular directive to delete the last character when a change is made via ngModel

I have 2 input fields where I enter a value and concatenate them into a new one. Here is the HTML code: <div class="form-group"> <label>{{l("FirstName")}}</label> <input #firstNameInput="ngMode ...

Using forkJoin() to introduce a delay between asynchronous API calls

Here is the code snippet I am currently working with: return forkJoin( pages.map( i => this.http.get(`devices?page=${i}&size=8000`) ) ).subscribe((event: any) => { event.forEach((entry) => { ...