Is it better to subscribe or utilize backing properties to update dependent data within a component?

I struggle with determining the most effective practices for Angular.

The issue I am facing is as follows:

<div>
   <app-child [data]="data | async"> 
   </app-child>
</div>

Should I opt for the following option:

A: Utilize Backing properties to update a correlated value

class ChildComponent{
     @Input 
     set data(value){
        this._data =value;
        this.label = this.labelService.getLabelColor(value.warningperiod)
     }
     get data(){ return this._data}
     _data: object;

     labelColor:string
     // constuctor... 
}

B: Use Observables and subscriptions

<div>
   <!-- pass down the whole observable -->
   <app-child [data]="data"> 
   </app-child>
</div>
class ChildComponent implements OnInit{
     @Input data: Observable<object>;
      labelColor: String;
      onInit(){
         this.data
         .subscribe( value =>{
              this.labemColor= this.labelService.getLabelColor(value.warningPeriod)
          }) 
      }
      //constructor
     
}

Which approach is more beneficial?

The need to unsubscribe when subscribing can be seen as "annoying."

When should I choose one over the other?

Answer №1

When working with asynchronous data, using the AsyncPipe is the preferred option as it eliminates the need to manually handle unsubscribe actions (thus preventing memory leaks) and allows changes to be detected in the background.

However, if you need to modify the data or perform certain actions after receiving new data, subscribing in the TypeScript file (.ts) may be more suitable. Just remember to unsubscribe properly, especially when using ChangeDetectionStrategy.OnPush, where you will also need to run detectChanges.

In general, utilizing the AsyncPipe is recommended for most scenarios, reserving manual subscription only for cases where it is absolutely necessary.

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

Encountering TS2322 error when defining a constructor in Angular 2 with ag-grid

Currently, I am following a tutorial I stumbled upon online titled Tutorial: Angular 2 Datatable with Sorting, Filtering and Resizable Columns. It appears to be the most straightforward guide to help me get started with the ag-grid library before delving d ...

Dealing with .env.local in a next.js TypeScript file: best practices

import GithubProvider from "next-auth/providers/github" import GoogleProvider from "next-auth/providers/google" const GITHUB_ID: string = process.env.GITHUB_ID as string; const GITHUB_SECRET: string = process.env.GITHUB_SECRET as strin ...

Using Express middleware in a TypeScript Express application

I'm currently converting the backend of an ExpressJS application to Typescript. While working on the auth.routes.ts file, I encountered an issue with the middleware (authMiddleware). It seems like there might be a typing error, as the same code in the ...

Optimize Next.js 10 TypeScript Project by Caching MongoDb Connection in API Routes

I am currently in the process of transitioning next.js/examples/with-mongodb/util/mongodb.js to TypeScript so I can efficiently cache and reuse my connections to MongoDB within a TypeScript based next.js project. However, I am encountering a TypeScript err ...

The React build script encounters issues resolving node modules while operating within a Docker environment

I'm currently in the process of dockerizing a React app that was initially created using CRA (Create React App) with TypeScript manually added later on, rather than through CRA. My file structure looks like this: <my app> ├── node_modules ...

I am encountering an issue with importing modules from the public folder in Next.js when using TypeScript, as I am

I've been running into an issue with importing files in Next.js using TypeScript. I'm trying to use regular imports with custom absolute paths, but I keep getting a module not found error. Oddly enough, my IDE is able to locate the file when I cl ...

Is it possible to configure a unique Bearer Access Token in the "angular-oauth2-oidc" library?

For my Facebook login, I have set up a custom endpoint where the client sends the Facebook access token. In my Ionic App, I use the '@ionic-native/facebook/ngx' package to retrieve this token. Within a Laravel Json API controller, I utilize Soci ...

Having trouble accessing the ngx-bootstrap datepicker directive through ViewChild

How can I implement a datepicker that hides when a scroll event occurs? I found a solution using ngx-bootstrap-datepicker Although it works on Stackblitz, it does not work in my application. Here is the code snippet: HTML <div *ngIf="isEditAuth&q ...

What causes the child component to be rendered four times when the parent component is first loaded?

I have been facing an interesting scenario with my parent and child components. Typically, change detection is triggered by events like HTTP requests or timers such as setInterval and setTimeout. However, in this particular case, I am not utilizing any of ...

Aligning items on Mat-Toolbar (left, center, and right)

I created a new toolbar but I am having trouble aligning the elements on the same line in different positions such as left, center, and right. Is there anyone who can provide guidance on how to achieve this alignment? In my observation, elements with the ...

Utilizing the PATCH method with Dropwizard to remove a designated item from a list that is a part of another list

Currently, I am working on developing a PATCH API method that can remove a specific element from a list of items. This list of items is an integral part of the Menu class in my project. Unfortunately, there is a scarcity of Dropwizard resources available o ...

What steps do I need to take to integrate fluent-ffmpeg into my Angular 8 project?

I have integrated the 'fluent-ffmpeg' plugin into my project and included it in my angular project like this: var ffmpeg = require('fluent-ffmpeg'), and I also tried using import * as ffmpeg from 'fluent-ffmpeg' However, I en ...

Angular Validators are behaving inconsistently, as they only work intermittently before stopping altogether once the application is

Why does my code sometimes behave differently after running for a while and then return to normal after restarting the Angular server without making any changes?The pop-up that says "please fill out this field" disappears when it shouldn't This is th ...

Tips on extracting a base64 image from a canvas

I have successfully developed a function that is capable of reading an uploaded image and extracting imageData from the canvas. However, I am encountering difficulty in obtaining the base64 image from that imagedata. Here is my code snippet: function han ...

What strategies should be employed to develop an Angular 4 application seamlessly integrated with Asp.NET Core?

I attempted to test out a couple of templates which turned out to be unsuccessful: https://github.com/asadsahi/AspNetCoreSpa https://github.com/MarkPieszak/aspnetcore-angular2-universal Unfortunately, neither of them worked properly for me. I'm cu ...

An error persists in PhpStorm inspection regarding the absence of AppComponent declaration in an Angular module

After creating a new Angular application, I am encountering the issue of getting the error message "X is not declared in any Angular module" on every component, including the automatically generated AppComponent. Despite having the latest version of the An ...

The type '(props: Props) => Element' cannot be assigned to the type 'FunctionComponent<FieldRenderProps<any, HTMLElement>>' in React-final-form

I'm fairly new to using TypeScript, and I am currently working on developing a signUp form with the help of React-Final-Form along with TypeScript. Here is the code snippet that describes my form: import React from "react"; import Button from "@mater ...

Creating a distinct Output type in Typescript to avoid any confusion between Output arguments and Input arguments

Inspired by C#, I am looking to define the following: type FunctionOutput<T> = T; // This is a basic implementation that needs improvement type Result = {result: number}; function myFun(a: number, b: number, c: FunctionOutput<Result>) { c.r ...

Issues with Angular 2 Cli setup

Exploring the world of Angular 2, I decided to dive into the installation process of angular2 cli. However, upon executing 'ng new newapp' after installation, an unexpected error appeared where 'mg' was referenced rather than 'ng&a ...

Upon utilizing the document.forms.input.value to assign a value, an Input Field now contains an undefined value

Currently, I am in the process of developing an Angular Application and I am encountering a scenario where I need to edit the values within an array. The array is being displayed in a table format and when I click on the edit icon of a particular row, the ...