Manage both the return of an observable and the setting of a value within a single method using

I am in need of a service that can both return an observable and set a value to a field within the same method.

The current implementation of my userService.getUserDetails() method is as follows:

private requestUrl: string;
private bic: string;
private id: string;
private name: string;

getUserDetails(): Observable<User> {
this.bic = 'aaa';
this.id= '123';

this.requestUrl = `${configs.api}v1/bics/` + encodeURIComponent(this.bic) + `/ids/` + encodeURIComponent(this.id) + `/users`;

const userObservable = this.http.get<User>(this.requestUrl).pipe(catchError(this.handleError));

userObservable.subscribe(data => this.name = data.name);

return userObservable;
}

When calling getUserDetails, I aim to achieve two objectives: 1) Return Observable<User> 2) Set the name value for later access in other classes by injecting this service without re-triggering the http request. This is what I envision:

  getName() {
return this.name;
 }

However, I am uncertain about using subscribe because I encounter undefined values when attempting to use the stored value. What would be the most appropriate approach to tackle this issue?

Answer №1

Here is an example of how to utilize the observable:

   public name: string;
   public bic: string;
   public id: string;

   public getUserDetails(): Observable<User> {
        this.bic = '...';
        this.id = '...';
        this.requestUrl = `${configs.api}v1/bics/` + encodeURIComponent(this.bic) + `/ids/` + encodeURIComponent(this.id) + `/users`;

        return this.http.get<User>(this.requestUrl).pipe(catchError(this.handleError));
    }

It's best practice for this method to be in a service, solely responsible for returning the observable and handling errors.

In your component, you can implement it like so:

    constructor(private readonly _yourService: YourService) {}

    public ngOnInit(): void {
    this.getUserDetails();
    console.log(this._yourService.name) // may output undefined as the observable execution is asynchronous
    }

    public getUserDetails(): void{
    this._yourService.getUserDetails().subscribe(
    data => {
    this._yourService.name = data.name;
    // continue with other operations as now this.name should hold the expected value.
    }
    )
    }

Alternatively, you have the option to handle all these tasks within the service itself. Ultimately, the decision lies with your design preferences.

Answer №2

Implement the use of "tap" in your service

name:any;
const userObservable = this.http.get<User>(this.requestUrl).pipe(
tap((res)=>{
    this.name=res;
}),
catchError(this.handleError)
);

Occasionally, a form of "cache" is utilized

name:any;
const userObservable = (this.name)?of(name):
  this.http.get<User>(this.requestUrl).pipe(
    tap((res)=>{
      this.name=res;
    }),
      catchError(this.handleError)
    );

You have the ability to subscribe to the function at any time. The initial call triggers an HTTP request, while subsequent calls utilize the value stored in "name" - of(name) returns an observable.

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

Issue with TypeORM @BeforeInsert causing a field in Entity not to be populated with value

Currently, I am facing an issue where I am attempting to update or insert into a token field before the record is saved. However, when utilizing the @BeforeInsert hook, I encounter the following error: "error": "Cannot read property 'co ...

Steps for importing jQuery to vendor.ts in Angular 2 webpack

Currently, I am in the process of setting up my Angular 2 app using webpack. As I review the vendor.ts file, I notice this specific structure. // Angular 2 import '@angular/platform-browser'; import '@angular/platform-browser-dynamic'; ...

The URL is reverted back to the previous address

Currently in the process of developing an Angular application, I've encountered a minor visual issue. On one of the pages, there is a ReactiveForm implemented, but whenever I navigate to that page, the URL reverts back to the previous one (even though ...

Generating Angular components dynamically in batch

I have a collection of diverse data objects: const arr = [ {type: 'CustomA', id: 1, label: 'foo'}, {type: 'CustomB', src: './images/some.jpg'} {type: 'CustomX', firstName: 'Bob', secondNa ...

Having trouble with subscribing to a template in Ionic framework

I'm attempting to showcase an image from Firebase storage using the following code: Inside my component : findImg(img) { this.storage.ref('/img/' + img).getDownloadURL().subscribe( result => { console.log(result); ...

Sending an HTTP POST request to an iFrame

I am currently working on integrating my website with a third-party white-label site that can be hosted in an iFrame on my website. To ensure the correct loading of the website within the iFrame, I need to send an HTTP POST request with credentials to a s ...

JavaScript heap ran out of memory near heap limit during mark-compacts, rendering the allocation ineffective, resulting in a failed Ionic 3 production build

While attempting to build a production version of my Ionic 3 app, I encountered the following error: "FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory". To troubleshoot this issue, I duplicated the en ...

ReactJs Error: Unable to access property value because it is undefined (trying to read '0')

I am currently attempting to retrieve and display the key-value pairs in payload from my JSON data. If the key exists in the array countTargetOptions, I want to show it in a component. However, I am encountering an error message stating Uncaught TypeError ...

You are able to set up the booking.com form once but cannot do so again using the ngOnInit method

Currently, I am utilizing angular materials in conjunction with angular4. Within an MdDialogue component, I have embedded HTML code for a booking.com form. The intention is for this dialogue box to appear with the form inside whenever a button is clicked. ...

Receiving data from submitted forms in Qt using QNetworkRequest

In my Qt widget application, I am utilizing a QWebView component. As part of this setup, I have established a network manager to manage incoming requests from the QWebView. My goal now is to capture the data inputted into web forms within the QWebView. At ...

Styles brought in from external sources do not get applied to components

My goal is to create a separate file specifically for storing styles targeted at IE 9-11. In order to achieve this, I have created a file named InternetExplorer.scss and imported it into my main file styles.scss: @import "scss/InternetExplorer.scss"; The ...

Trouble fetching post data with $http.post in AngularJs & Web API integration

Here is my implementation of a web api method: // POST api/Account/Register [AllowAnonymous] [Route("Register")] public async Task<HttpResponseMessage> Register([FromBody] string data) { //data always returns null } O ...

The MSI installer for electron-builder is rejecting the asar file due to its excessive

My Angular application requires an MSI installer, but I encountered an error while trying to create one for the electron app I developed using `npm run electron`. The error message states: Error LGHT0263 : 'C:...\release\win-unpacked&bsol ...

Property-based Angular Material row grouping in a mat-table is a powerful feature that enhances

Is there a way to organize the data in one row with the same ID? Currently, my data looks like this: Data Set: { "id": "700", "desc": "Tempo", "richiesta": "20220087", "dataElab": &quo ...

Dynamic Route Matching in NextJS Middleware

Currently, I am in the process of developing a website that incorporates subdomains. Each subdomain is linked to a file-based page using middleware. Take a look at how the subdomains are being mapped to specific pages: app.com corresponds to /home app.com ...

Encountered a bun runtime error stating "Possibly require an `extends React.JSX.IntrinsicAttributes` constraint for this type parameter."

I have a good understanding of ReactJS, but this topic seems to be more advanced. I am working with generics in TypeScript and have the following code: export const withPopover = <T,>(WrappedComponent: React.ComponentType<T>) => { const ...

What is the best way to compare an array with comma-separated values in JavaScript?

I have a scenario where I have two arrays, one for categories and the other for products. Each product contains multiple categories as a comma-separated string. My goal is to match a specific category with each product's product_category value and the ...

Discovering the breakpoints for Angular ng-bootstrapUncover the angular ng

Utilizing ng-bootstrap in my latest project has allowed me to easily create a grid with breakpoints, like so: <div class="row"> <div class="col-sm-12 col-md-6 col-xl-4"></div> </div> Although these breakpoints are convenient, ...

Error message: Cordova not found - unable to use 'ionic native' 3 for CRUD operations with SQLite database

I am attempting to manage CRUD data with SQLite in Ionic 3, but unfortunately cordova is not functioning as expected. https://i.sstatic.net/5m411.png ...

Troubleshooting issue: Unable to display data using *ngFor in Angular 4

Currently, I am developing an application that utilizes HttpClient to fetch data from a local JSON file. The JSON file contains images and descriptions, with the images also being local. While I am able to successfully log the data in a local array, I am e ...