Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i share data from http Response between components?

I'm develop an app which it should make http request to a third Api. When i make the authetication process, the Api provides me a key (it calls clientid) which i have to post with other data to future http requests.

So the case is that after authetication to the Api, when i want to make any other request i have to post the clientid that i took from the authentication response.

I read about parent-child relationship (@input-@output) but i think that does not helps, because the App will make different request from different components which they may have no relation between them.

My idea is that, when i finish with the authetication process from the respective services i had to store somewhere this field in order to be available when i want to make other request from any compoment i need.

I think that i need something like singleton approach but i am not sure about the propriety of the thought.

like image 529
Dimitris Avatar asked Jun 05 '26 18:06

Dimitris


1 Answers

You're going to want to have a service that makes the request and stores the data. Here's an example of a simple service that makes an HTTP request for some data that is an array of strings.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of, tap } from 'rxjs';

Injectable({
    providedIn: 'root'
})
export class MyExampleService {
    private myData: string[] = [];

    constructor(private readonly http: HttpClient) { }

    getData$(): Observable<string[]> {
        //if we already got the data, just return that
        if (this.myData.length > 0) {
            return of(this.myData);
        }

        //if not, get the data
        return this.http.get<string[]>('http://my-api.com/get-stuff')
            .pipe(tap((returnedData: string[]) => {
                //save the returned data so we can re-use it later without making more HTTP calls
                this.myData = returnedData;
            }));
    }
}

then in your angular components, they can both request data in the exact same way, but only the one that does it first will actually make the HTTP request, the others will just get the already cached data.

import { Component, OnInit } from '@angular/core';
import { MyExampleService } from '../services/my-example.service';

@Component({
    selector: 'app-my-example',
    templateUrl: './my-example.component.html'
})
export class MyExampleComponent implements OnInit {
    theData: string[] = [];

    constructor(private readonly myExampleService: MyExampleService) {}

    ngOnInit(): void {
        //call the service
        this.myExampleService.getData$()
            .subscribe((data: string[]) => {
              //when sucessful, data is returned here and you can do whatever with it
              this.theData = data;
            }, (err: Error) => {
                //When unsuccessful, this will run
                console.error('Something broke!', err);
            });
    }
}
like image 120
FiniteLooper Avatar answered Jun 07 '26 13:06

FiniteLooper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!