Angular 2: The Battle of Async Pipes Versus Using a Single Subscribe

Which approach is more optimal for performance and aligns better with the "angular way": using multiple async pipes in the view or having a single subscriber in the component with an onDestroy unsubscribe action?

For example:

@Component({
  template: `<div> {{ post.title }} {{ post.author.name }} {{ post.category.name }} </div>`
  ...
  })
class AppComponent {
  public post: Post;
  public postSubscription;

  ngOnInit() {
    postSubscription = someObservable.subscribe((post) => {
      this.post = post;
    })
  }

 ngOnDestroy() {
    postSubscription.unsubscribe();
 }
}

or

@Component({
  template: `<div> {{ postTitle | async }} {{ postAuthorName | async }} {{ postCategoryName | async }} </div>`
  ...
  })
class AppComponent {
  public postTitle: Observable<string>;
  public postAuthorName: Observable<string>;
  public postCategoryName: Observable<string>;

  ngOnInit() {
    this.postTitle = someObservable.pluck('title');
    this.postAuthorName = someObservable.pluck('author', 'name');
    this.postCategoryName = someObservable.pluck('category', 'name');
  }
}

Answer №1

Optimizing performance in Angular can be achieved by utilizing the | async pipe, as it allows Angular to receive notifications about any changes. In contrast, when using the initial approach, the bindings are scrutinized during each cycle of change detection.

Answer №2

What an intriguing inquiry! I've frequently found myself pondering the choice between employing multiple async pipes for a single observable versus subscribing in the OnInit method and unsubscribing in the OnDestroy method.

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

Manipulating content with JavaScript in Internet Explorer using the outerHTML property is a powerful

Encountering an Issue with outerHTML in IE Browser If I try the following: txt = "Update Complete!"; msg = sub.appendChild(d.createElement("p")); msg.outerHTML = txt; It works without any problem. However, if I use: txt = "1 Error:<ul><li> ...

Is PhoneGap solely reliant on UIWebView or does it incorporate additional features? Possibly Nitro integration?

Is PhoneGap limited to using UIWebView, or does it offer additional functionality beyond that? Does PhoneGap utilize Apple's Nitro VM technology? I am in the process of exploring options for converting our JavaScript app to a native format. I am com ...

Which is Better for Creating DropDown Menus: CSS or JavaScript?

Starting a new project that involves dropdown menus with categories and subcategories within them. I'm curious about the advantages of using CSS3 only menus compared to traditional JavaScript ones. There are several jQuery menu options available as we ...

Having trouble applying CSS styles to an element using JavaScript

Hello, I have an unordered list with some list elements and I am trying to apply a CSS style to highlight the selected list element. However, the style is not taking effect as expected. function HighlightSelectedElement(ctrl) { var list = document.ge ...

Assemblage of Marionettes: Adding multiple elements to the DOM

I am working on a Marionette application and have come across an issue with inserting new tab items. I have a collection of tabs, but when adding a new item, I need to insert DOM elements in two different areas. The problem is that Marionette.CollectionV ...

Create and set up a dynamically added Xeditable form field

Is there a way to add a dynamic editable field within the thumbnail section of dropzone.js? I have discovered that Xeditable fields added dynamically need to be initialized. I am attempting to do this in Angular. Check out the Fiddle here: http://jsfiddle ...

- "Variety of Hues in Google ColumnChart"

I am attempting to create a graph using data fetched from PHP code in the form of an array passed on to the draw function. The colors display correctly when I use PieChart, but not for ColumnChart. How can I make the bars appear in different colors? Below ...

Is it possible to consolidate geometry in each frame during the rendering process using three.js?

Having recently delved into three.js, I've been experimenting with some concepts. My current challenge involves creating a line in the scene and using it as a reference for cloning and transforming. The goal is to display the cloned lines in a sequent ...

What is the process for uploading a file in binary format using the ng-file upload library in AngularJS?

While trying to upload a file to Amazon S3 Bucket using a pre-signed URL from AngularJs, I encountered an issue where the zip file ended up getting corrupted. Interestingly, everything worked as expected when I uploaded the file from Postman in binary form ...

Include category to the smallest element

I am attempting to use JQuery to find the height of the tallest element and then add that height to other elements that are shorter. My goal is to assign the class, main-nav-special-padding, to these shorter elements using my current JQuery code. I tried t ...

Identifying the Clicked Object in JavaScript

I have a simple movie search feature, but now I want to improve it so that when a user clicks on a movie, only that specific movie's title property is displayed. Currently, every movie that matches the search term is being shown. How can I identify w ...

Issues with the functionality of angular-oauth2-oidc tryLogin() are causing unexpected results

In my angular 8 project, I am using release version 8.0.4 with the authorization code flow implemented: Below is the code snippet that I have in place this.oauthService.configure(authConfig); this.oauthService.tokenValidationHandler = new JwksVali ...

Concealing a VueJs component on specific pages

How can I hide certain components (AppBar & NavigationDrawer) on specific routes in my App.vue, such as /login? I tried including the following code in my NavigationDrawer.vue file, but it disables the component on all routes: <v-navigation-drawer ...

Can the route.meta property be accessed from outside the component?

I've encountered an issue with using the route.meta property in my Vue 3 project. Initially, I had it working inside a Vue component, but when I moved the code into a .ts file, it stopped functioning and an error appeared in the browser. Here is my . ...

Developing a collection of customized shapes comprised of circular-edged rectangles using the Three.JS

I have been on a quest for some time now. My aim is to replicate this visual element from - the beautifully arranged deck of cards. I know it was created using Three.JS, and my goal is to recreate it exactly as seen in that link. The challenge I'm c ...

What is the best way to manage classNames dynamically in React with Material-UI?

I am wondering how to dynamically add and remove classes from an img tag. My goal is to change the image automatically every 2 seconds, similar to Instagram's signup page. I am struggling to achieve this using the material-ui approach. Below is a snip ...

Obtain a reference to a class using a method decorator

My goal is to implement the following syntax: @Controller('/user') class UserController { @Action('/') get() { } } Now in the definition of decorators: function Controller (options) { return function(target: any) { let id ...

CORS response header is not included

Is it the company's responsibility () to rectify one of their endpoints or is it an issue with my code? I have tested all other endpoints () using the same code below and they all function correctly, except for the specific one in question. The erro ...

"Upon invoking the console log, an empty value is being returned when attempting to access the

Why is console.log returning a blank line when trying to retrieve the value of a text input variable? HTML <label for="subject">Subject</label> <input type="text" id=" ...

Is there a way to alter an array through a reference within a function?

I am working with a function that looks like this: public recursiveFilterLayers(node: LayerNode[]): LayerNode[] { const validItem = node.filter( (i) => i.visible === true || i.visible === undefined ); validItem.forEach((i) => { ...