Set the component variable to hold the output of an asynchronous method within a service

As I work on developing an application, I aim to keep my component code concise and devoid of unnecessary clutter. To achieve this, I plan to offload complex logic into a service which will then be injected into the component. Suppose my component includes a variable called 'result':

my.component.ts

    .....

    private result:number;

Meanwhile, my service houses an asynchronous method:

my.services.ts

    ......
    ......

    getNumberFromApi(){
    callAsync().subscribe( data => {
        console.log('This is the data obtained..'+data);
    })

I wish for the ability to pass a parameter to the getNumberFromApi() method:

    getNumberFromAPI(destinationVar:number){
    callAsync().subscribe( data => {
        console.log('This is the data obtained..'+data);
        destinationVar=data;
    })
    

This would enable me to invoke the service's method from within the component as follows:

my.component.ts

    .....

    private result:number;
    myServiceInstance.getNumberFromApi(result);

While I am aware that directly modifying component variables from async methods may not be feasible due to stack limitations, I remain eager to explore alternatives. Is there a way in Typescript/Angular to effortlessly update component variables from services without adding extraneous lines of code? Your insights are greatly appreciated. Thank you.

Answer №1

To maintain the asynchronous nature of an observable, you should ensure that you return and subscribe to it in both the service and component respectively. By doing so, you can effectively make API calls with varying parameters as needed.

Service

import { Observable } from 'rxjs';

getNumberFromApi(): Observable<any> {
  return callAsync();
}

Component

export class SomeComponent implements OnInit {
  someVar: any;

  constructor(private someService: SomeService) { }
  
  ngOnInit() {
    this.someService.getNumberFromApi().subscribe({
      next: (value: any) => this.someVar = value,
      error: (error: any) => { }
    });
  }
}

If the someVar variable in the component is solely used for rendering data in the template, you could opt for using Angular's async pipe instead of subscribing directly in the controller.

Controller (*.ts)

import { Observable } from 'rxjs';

export class SomeComponent implements OnInit {
  someVar$: Observable<any>;   // <-- dollar sign typically denotes observables

  constructor(private someService: SomeService) { }
  
  ngOnInit() {
    this.someVar$ = this.someService.getNumberFromApi();
  }
}

Template (*.html)

<ng-container *ngIf="(someVar$ | async) as someVar">
  <!-- utilize `someVar` here -->
  {{ someVar }}
</ng-container>

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

Exploring child components through auxiliary routing in Angular

After defining the root routing as shown below: const routes: Routes = [{ path: '', component: HomeComponent }, { path: 'module1', loadChildren: './module1/module1.module#Module1Module' }, { path ...

What is the best way to run tests on this method using Jest?

import { format, getDaysInMonth, getMonth, getYear, isValid, parse } from "date-fns"; export class DateService { public getDaysInMonth(month?: Date) { return getDaysInMonth(month || new Date()); } What is the best way to test this func ...

Guide to summing the values in an input box with TypeScript

https://i.stack.imgur.com/ezzVQ.png I am trying to calculate the total value of apple, orange, and mango and display it. Below is the code I have attempted: <div class="row col-12 " ngModelGroup="cntMap"> <div class="form-group col-6"> ...

Can builtins like DOM globals be explicitly imported?

The present situation includes the utilization of rollup (as well as iife parameters), but I am hesitant about whether it is solely related to rollup or typescript. My objective is to achieve something similar to this: import { document } from "[wherever ...

What is the proper way to integrate helmet.js with typescript?

Utilizing helmet from pure JavaScript according to the documentation is quite straightforward: const express = require('express') const helmet = require('helmet') const app = express() app.use(helmet()) However, I'm unsure how ...

verifying the date in a specific moment

Is there a way to validate the date accurately? to determine whether she cleared it or not. I've exhausted all my options. Despite reading through the documentation, I am unable to get it right. Here is what I attempted: if ('2023-03-03 ...

Getting data from posts using RESTful web services in Java

Currently, I am receiving a JSON object POST request from Android Volley. In an attempt to interpret the JSON data, I have implemented the code shown below. @POST @Path("/driver/insertTripLog") @Consumes(MediaType.APPLICATION_JSON) @Produc ...

The error message TS2304 is indicating that the name 'Set' cannot be found in electron-builder

I am trying to utilize the AppUpdater feature in electron-builder for my Electron Application. Upon importing the updater in my main.ts file: import { autoUpdater } from "electron-updater" An error is triggered when running the application: node_module ...

The browser does not store cookies in its memory

After conducting extensive research on this issue, I have not been able to find a solution yet. In essence, I am currently running a Node.js API server on localhost:3000 and an Angular 10 app on localhost:4200. The problem is straightforward - when I make ...

Having trouble adding information to the database with PDO?

Despite successfully sanitizing and validating the input data, I encountered an issue when trying to insert it into my database. Each time I attempt to do so, an error message pops up: "Sorry, we were not able to sign you up... Refill the form properly" $ ...

Tips for correctly linking an Event Listener to the worldwide 'window' in Angular 6 and higher

Situation Within our Angular 6 application, an iframe is embedded to showcase third-party data. To facilitate secure cross-domain communication, the child iframe sends messages to the parent Angular app using window.postMessage() API. To receive these mes ...

Just completed the upgrade of my Angular project from version 9 to version 12, but now encountering issues with a module that utilizes Plotly

Here is the content of my app module file. All components and imports are in their respective places as specified in the documentation: import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from &apos ...

Creating a package containing an Angular 2 application combined with Express

I recently completed a regular Angular CLI project using webpack for production. After bundling the project, I transferred the contents of the dist folder to another project where Express was installed. var express = require('express'); var app ...

How can I iterate through a variable in TypeScript?

initialize() { var elements = []; for (let i = 1; i <= 4; i++) { let node = { name: `Node ${i}` }; elements.push({ [`node${i}`]: node }); if (i < 4) { let edge = { source: `node${i}`, target: ...

Using @HostBinding based on the @Input() condition

I'm attempting to link the CSS class foo to my parent component by utilizing @HostBinding based on a condition I evaluate against a dynamic variable. However, I am struggling to get it to function as expected. Here are the different approaches I hav ...

Struggling with loading partials in Sails.JS from the "assets" directory?

I am currently using Sails.JS as the backend paired with Angular 6 for the frontend of my application. Within my homepage.ejs file, I am trying to load HTML content from the assets folder: <!DOCTYPE html> <html> <!-- webpack generated ht ...

Ensuring that files adhere to the required format, whether they be images

Three separate input fields are being used, each with its own name for identification. A validation method is called to ensure that the files selected in these input fields are not duplicates and that they are either images or PDFs but not both. While thi ...

Is Angular's ngOnChanges failing to detect any changes?

Within one component, I have a dropdown list. Whenever the value of the dropdown changes, I am attempting to detect this change in value in another component. However, I am encountering an unusual issue. Sometimes, changing the dropdown value triggers the ...

How to make an HTTP request only once after a certain period of time

I have an Angular 11 component with multiple dynamically included inputs in a table. After the user enters a currency value into any of these inputs, I make an API call to calculate the total. The issue is that I am calling the API multiple times, so I wa ...

"Utilizing ReactJS and Typescript: A guide on initiating a Redux dispatch event through an axios

Looking for help with ReactJS typescript and redux dispatch events when calling APIs using axios interceptors? Check out my code snippet below. Codesandbax Repo App.tsx import "./App.css"; import "bootstrap/dist/css/bootstrap.min.css" ...