Executing a Function in a Service from a Component in Angular/TypeScript and Receiving a Return Value

I need guidance on how to effectively utilize the "getUserDocInfo()" function from a separate service within my component. How can I call this function and then leverage the data it returns for further operations?

Component Example

 getToken(){
    this.userService.getUserDocInfo();
    // Once the data is returned, I want to extract and use certain values
  }

Service Implementation

getUserDocInfo() {
    this.getUserInfo().then(() => {
      this.userDoc = this.afs.doc(`users/${this.userID}`);
      this.user = this.userDoc.snapshotChanges();
      this.user.subscribe(value => {
        const data = value.payload.data();
      });
    })
  }

 async getUserInfo() {
    const user = await this.authService.isLoggedIn()
    if (user) {
      this.userID = user.uid;
    } else {
      // Handle alternative scenario
    }
  }

If you have any tips or best practices to share regarding this scenario, please feel free to offer your suggestions.

Answer №1

If you're looking to accomplish this, one approach is to set up a callback function that can be passed as a parameter in the method. Here's an example:

getUserDocInfo(callback) {
    this.getUserInfo().then(() => {
      this.userDoc = this.afs.doc(`users/${this.userID}`);
      this.user = this.userDoc.snapshotChanges();
      this.user.subscribe(callback);
    })
  }

getToken(){
    this.userService.getUserDocInfo((value) => {
        console.log(value.payload.data());
    });
  }

Another option is to return an Observable and then subscribe to it within your component context for more customized handling.

import { Observable } from 'rxjs/Observable/';
import 'rxjs/add/observable/fromPromise';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/mergeMap';

@Injectable()
export class AlertService {

  //constructor and properties...

  getUserDocInfo(): Observable<any> {
    Observable.fromPromise(this.getUserInfo()).mergeMap(() => {
      this.userDoc = this.afs.doc(`users/${this.userID}`);
      this.user = this.userDoc.snapshotChanges();
      return this.user.map(user => user);
    });
  }
}

@Component(...)
export class MyComponent implements OnDestroy {

  subscriptions: Array<Subscription> = new Array;

  //constructor

  getToken(){
    const sub = this.userService.getUserDocInfo().subscribe((value) => {
        console.log(value.payload.data());
    });
    this.subscriptions.push(sub);
  }

  ngOnDestroy() {
    this.subscriptions.forEach(sub => sub.unsubscribe());
  }
}

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 there a way to determine the distance in miles and feet between various sets of latitude and longitude coordinates?

I am working with an array of latitude and longitude coordinates and I am looking to use JavaScript or Typescript to calculate the distance in miles and feet between these points. const latsLngs = [ { lat: 40.78340415946297, lng: -73.971427388 ...

Explore the features of Angular4 including the router and optional children parameters

I am interested in creating paths like these: matches/:page/:team/:season with the flexibility of having :team and :season as optional parameters. For example, I would like to be able to use URLs such as: matches/results/4/2017 or matches/results/4 or ...

Problem with the Auto-fill Feature in PrimeNG Module

Check out my code on Gist:   https://gist.github.com/rickymuvel/8ddc4d14d90877329447ddde9c0aa835 The issue I'm facing involves the Autocomplete module in PrimeNG. It seems that the specific path in the ubigeo.service.ts file is not being called. Her ...

Modifying the form-data key for file uploads in ng2-file-upload

I have implemented the following code for file upload in Angular 2+: upload() { let inputEl: HTMLInputElement = this.inputEl.nativeElement; let fileCount: number = inputEl.files.length; let formData = new FormData(); if (fileCount > 0) { // a f ...

The message states that the variable "Chart" has not been defined

I have been attempting to integrate ChartJS with Angular2, but I keep encountering an error message stating that 'Chart is not defined'. I made sure to install the ChartJS typings and referenced them accordingly. Additionally, I included the char ...

How to open a print preview in a new tab using Angular 4

Currently, I am attempting to implement print functionality in Angular 4. My goal is to have the print preview automatically open in a new tab along with the print popup window. I'm struggling to find a way to pass data from the parent window to the c ...

Employing 'as' in a similar manner to *ngIf

Utilizing the *ngIf directive, one can simplify code by assigning a property from an observable using syntax like *ngIf = (value$ | async).property as prop . This allows for the use of prop throughout the code without repeated references to (value$ | async ...

The test suite encountered an error (EBUSY: resource busy or locked) and unfortunately failed to run at Nx version 14.5.10 and Jest version 27.5.1. It seems there was an

I have recently upgraded my NX Monorepo from version 13 to 14, and everything seems to be working fine except for the Jest migration. I keep encountering this error even after trying various solutions like clearing the cache, deleting node_modules, and rei ...

Printing content from an Angular dashboard can be achieved by following a few

Currently, I am working on developing a legal document automation program for my company. However, I have encountered an issue during the final stages of completing this web application. For the layout and setup, I am using the default angular Dashboard l ...

Differentiating Views for a Single URL in Angular 6: Enhancing Progressive Web Apps

Below is the content from my app-router.module.ts import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { DheaderComponent } from './dheader/dheader. ...

What is the process for connecting a form to a model in Angular 6 using reactive forms?

In the time before angular 6, my approach involved utilizing [(ngModel)] to establish a direct binding between my form field and the model. However, this method is now considered deprecated (unusable with reactive forms) and I find myself at a loss on how ...

Do you notice a discrepancy in the number returned by Javascript's Date.getUTCDate() when the time component is set to

Consider the following code snippet: const d = new Date('2010-10-20'); console.log(d.getUTCDate()); If you run this, the console will output 20. However, if you modify the code like so: const d = new Date('2010-10-20'); d.setHours(0, ...

Unable to create a line break within an ion-item

I'm facing a bit of a dilemma with this straightforward issue. Can't seem to find a solution. The following code is not producing the desired outcome: <div text-wrap ion-item no-lines> "No result found. <br/> Please ent ...

Troubleshooting issue of incorporating hintText in a TextField within a create-react-app-with-typescript

After recently downloading, installing, and running the create-react-app-with-typescript, I have been exploring different components. My latest experiment involved adding a TextField with hintText using the following code: import TextField from 'mate ...

What is the correct way to implement Vue.use() with TypeScript?

I am trying to incorporate the Vuetify plugin into my TypeScript project. The documentation (available at this link) suggests using Vue.use(), but in TypeScript, I encounter the following error: "error TS2345: Argument of type '{}' is not assign ...

Deploying an Angular application in a NodeJS environment using Azure DevOps

Can Azure DevOps Pipelines be used to automate the deployment of an Angular application to NodeJS or an on-premise WebServer? ...

Angular: Card disabled post-click

I am displaying three cards <div *ngFor="let catalog of catalogs;let i=index" (click)="goToProducts(catalog)"> <div> <div class="name-position text {{catalog.classe}}" style="font-size: 21px;"> ...

Calculating the number of days between two given dates, including both the start and end dates

I need to calculate the number of days between two dates, including both of the dates. My current method for this task is as follows: numDaysBetweenDates(startDate, endDate) { let millisecondsPerDay = 24 * 60 * 60 * 1000; return (endDate - startDate) ...

Attempting to eliminate any dates that have already occurred

I am faced with an array containing various dates in string format such as "2016-08-12". My goal is to eliminate any dates that have already passed by comparing them to today's date. I am using TypeScript for this task. Here is a snippet of my datoAr ...

A guide to securely retrieving data from the Hono API endpoint using type safety within a Next.js application

Currently, I am using Hono as my API endpoint with Bun. Now, I am working on a new app with Next.js and I want to ensure type safety when fetching data from my API. I believe I can accomplish this through RPC. However, I am unable to locate AppType mention ...