Angular asynchronous : no "| async" please

41 views
Skip to first unread message

Hervé Le Cornec

unread,
Oct 25, 2019, 8:46:49 AM10/25/19
to Angular and AngularJS discussion
Hello,

Many discussions here a related to the use of async data in Angular, so let me recall the basics.

Angular is natively designed to handle the async processes, because nearly everthing is async in javascript (loading, events, ...). To intend so Angular simply use the elvis operator "?.".

Here is an example of a component that retrieve async data and displays it :

1) The typescriptof the component (a timeout has been setup to simulate an async feed of the customer data)
import { ComponentOnInit } from '@angular/core';

@Component({
  selector: 'app-mycomponent',
  templateUrl: './mycomponent.component.html',
  styleUrls: ['./mycomponent.component.css']
})
export class MycomponentComponent implements OnInit {

  customerany;

  constructor() { }

  ngOnInit() {

    //Feed the customer variable asynchronously
    setTimeout(()=> {
      this.customer = {
        name: 'Bob',
        age: 25
      }
    }, 2000);

  }
}


2) The HTML template of the component
<ul>
  <li>Name : {{customer?.name}}</li>
  <li>Age : {{customer?.age}}</li>
</ul>

This is as simple as this. 
As you see there is no need for a "| async" in the template of the component, there is neither any need for a direct use of rxjs observables.

I hope this can help.
Cheers





Arnaud Deman

unread,
Oct 25, 2019, 11:42:24 AM10/25/19
to Angular and AngularJS discussion
Hi Hervé,

With the observables I find it very easy to use the async pipe: you don't have to subscribe, store the result, keep the subscription and unsubscribe when the component is destroyed.
I may have missed something but I use this extensively and I have not noticed any drawback yet.

Regards,
Arnaud.

Hervé Le Cornec

unread,
Oct 25, 2019, 12:16:20 PM10/25/19
to Angular and AngularJS discussion
Hello Arnaud,

I am not saying that your way of doing things does not work, I am sure that it works. I am also sure that, because you master it now, you code it fast, so you feel good with it.

I just say that you spent certainly more time to implement your way, than using the way that I describe. I pretend that your code is more complex than mine, with the disadvantages that will result.

Developping has a cost, increasing nearly exponentially with the complexity of the code. So the shortest code is the best. Angular has this of efficient that it reduces drastically the dev time, and so the occurence of bugs, and so the overall cost. So what I am saying is : do not reinvent the wheel, use the full potential of Angular.

Never forget that the aim is not "it must work" but "the user must be served ASAP with the highest quality, at the lowest cost".

Cheers
Reply all
Reply to author
Forward
0 new messages