Is there a way to enhance the functional purity by creating a single function that subscribes and returns a

I'm currently developing a project that involves receiving humidity data from a raspberry pi sensor connected to a backend. Within my Angular Component, I am aiming to display this data in a functional and pure manner. However, I have some doubts regarding my implementation and would greatly appreciate any feedback.

The getAllHumidities() function serves two purposes:

  • It subscribes to an Observable and returns the data in a functional way.
  • It also saves the Subscription as "humiditySubscription", albeit as a side effect.

I can't help but feel that the implementation of getAllHumidities() may not be following best practices. Is it possible to avoid creating the two component properties altogether?

export class HumidityListComponent implements OnInit, OnDestroy {

  humidities: Humidity[];
  humiditySubscription: Subscription;

  constructor(private humidityService: HumidityService) {

  }

  ngOnInit() {
    this.humidities = this.getAllHumidities();
  }

  getAllHumidities(): Humidity[] {
    let humidities: Humidity[];
    this.humiditySubscription = this.humidityService.getAll().subscribe(data => {
      humidities = data;
    });
    return humidities;
  }

  ngOnDestroy() {
    this.humiditySubscription.unsubscribe();
  }
}

Answer №1

Instead of using the getAllHumidities function, you can simplify by subscribing to your service in the onInit method.
By doing this, your humidities variable will always stay updated.

Give this a try:

humidities: Humidity[] = [];

constructor(
   public humidityService: HumidityService
) { }

ngOnInit() {
   this.humidityService.getAll().subscribe((data: Humidity) => {
      this.humidities = data;
   });
}

If you prefer a shorter version in your HTML:

<div *ngIf="(this.humidityService.getAll() | async) as humidities">
   // The slice pipe will display values from index 0 to 5
   <div *ngFor="let humiditie of humidities | slice:0:5; let i = index">
      Index: {{i}} <br> 
      Value: {{humiditie}}
   </div>
</div>

Answer №2

Understanding the purpose of the return value from the getAllHumidities() function can be a bit unclear. When subscribing, the humidity variable may only update after the function has completed its task.

An efficient way to retrieve and automatically unsubscribe from the observable is by utilizing the async pipe.

In the component:

humidities$: Observable<Humidity[]> = this.humidityService.getAll();

constructor(private humidityService: HumidityService) { }

ngOnInit() { }

In the HTML template:

<ng-container *ngIf="(humidities$ | async) as humidities">
...
use the fetched humidities
...
</ng-container>

For more information about async pipe.

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

Once the table is created in TypeORM, make sure to insert essential master data such as types and statuses

Hey there, I have a question regarding NestJS and typeORM. My issue is with inserting default values into tables after creating them. For example, I have a priority table where I need to insert High/Medium/Low values. Despite trying everything in the typeo ...

Include a description in the cell of the table

I am struggling with adding a small description below one of the columns in my three-column table. I have tried using Grid, but so far, nothing has worked for me. Can anyone provide assistance? To give you a better idea, I have highlighted the desired res ...

Tips for maintaining user sessions in Passport.js and PhoneGap: "remembering" a user after logging in

My Node.js server runs on the Sails.js framework, and I've successfully integrated passport.js to handle authentication. Here's how it works: (login)POST /auth/local: Validates credentials and returns ID, Username, and Email address. (register) ...

I am unable to retrieve values from the req.body object in Node.js

Can anyone assist with node.js? I am having trouble accessing the values in my req.body object. Here is how it is populated: { '{ "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="670a060e0b270f0814130906 ...

The error "Cannot invoke the indexOf method on an undefined element at order" is being encountered in Javascript

Looking for assistance with creating a function to sort a string where each word contains a single number from 1 to 9 (no 0). For instance, given the input: "is2 Thi1s T4est 3a", the desired output should be "Thi1s is2 3a T4est". The current code snippet ...

Stop Cross-Site Scripting Attacks by Sanitizing jQuery html()

After retrieving data from a database through ajax, I merge it with HTML code on the website using the .html() jQuery function. The process looks like this: $.ajax({ url: "getDatabaseData.php", type: "post", dataType: "json", success: func ...

The module './product' could not be located, resulting in error TS2307

app/product-detail.component.ts(2,22): error TS2307: Cannot find module './product'. I have tried several solutions but none of them seem to work for me. I am working on a demo app in Angular 2 and encountering this specific error. Any guidance ...

Updating the `link` function to target a specific DOM element within an Angular 2 component

Angular 1 uses the link function in a directive to target DOM elements. link: function (scope, element, attr) { // do something with element[0], e.g. put generated graphics // inside the node } What is the equivalent feature in Angular 2? ...

What is the best way for me to bring in this function?

Currently, I am in the process of developing a point-of-sale (POS) system that needs to communicate with the kitchen. My challenge lies in importing the reducer into my express server. Despite multiple attempts, I have been unable to import it either as a ...

What is the method for pulling information from MySQL and presenting it on a website using Node.js?

Currently, my goal is to retrieve data from MySQL and showcase it on my HTML page. The code snippet in server.js looks like this: const path = require('path'); const express = require('express'); const bodyParser = require("body-pa ...

How can I use PHP to transform a JSON object containing xy coordinates into an image?

What is the best way to convert a JSON object containing xy coordinates into an image (PNG or JPG) using PHP or JavaScript? ...

The sessionToken is invalidated upon the user updating their password

My mobile hybrid app is connected to an expressJS server that acts as the backend for proxying requests to parse.com through the REST API. Additionally, I have implemented user authentication using express with a Single Sign-On (SSO) provider. Although I f ...

The webpage is missing a rendered React component even though it should be displayed

I am facing an issue where a React component is not appearing on the webpage despite being rendered. I have provided the code and screenshots of the components below for reference. Below is the snippet from the "App.jsx" file: function createCard ...

Issues with JQuery list selectors

Many individuals have raised concerns about selectors in the past, but no matter what I try, my code seems right yet it doesn't work as intended. My situation involves a list of actions that are displayed or hidden when their corresponding "folder" is ...

React Hook Form: Reset function triggers changes across all controllers on the page

I encountered an issue with using the reset function to clear my form. When I invoke the reset function, both of my form selects, which are wrapped by a Controller, get cleared even though I only defined default value for one of them. Is there a way to pr ...

Removing specific text from a textarea containing a vast quantity of information

I developed a simple XML formatter using HTML and Javascript. I am looking to incorporate a delete feature into it. Essentially, I want the ability to remove an entry without affecting any other data. <contact <!--Jane Smith--> first_name="Jane" ...

In order to work with Mongoose and Typescript, it is necessary for me to

I am currently following the guidelines outlined in the Mongoose documentation to incorporate TypeScript support into my project: https://mongoosejs.com/docs/typescript.html. Within the documentation, there is an example provided as follows: import { Sche ...

React Native component that enables users to both input their own text and select options from a dropdown menu as they type

Looking to develop a component that combines Text Input and FlatList to capture user input from both manual entry and a dropdown list. Has anyone successfully created a similar setup? I'm facing challenges in making it happen. Here's the scenari ...

Recursive function in JavaScript with error handling using try-catch block

Within my nodejs script, I have implemented a system to generate dynamic tables and views based on the temperature data recorded for the day. On some occasions, the creation of these tables is hindered if the temperature falls outside of the normal range ...

What is the best method for toggling a class to indicate the active tab in VueJS?

My goal is to set the active class on the first <li> tab by default, and then switch it to the second <li> tab when selected. I plan to use CSS to visually indicate which tab is currently active. If you would like to see the current output, ch ...