DEV Community

Cover image for Tell Me I'm Wrong, Please (Angular and Async)
Shawn Wildermuth
Shawn Wildermuth

Posted on • Originally published at wildermuth.com on

Tell Me I'm Wrong, Please (Angular and Async)

I'll try and keep this quick. I'm updating one of my Pluralsight courses and I am curious if what I'm thinking makes any sense.

I've been teaching the same approach as most of the other Angular instructors, but I feel like it's not as clear as it should be. Let's look at a simple example of making a network call and showing state. I have a simple view that shows two strings. I am using a central service for calling the remote server with HttpClient. Here's the call using Reactive:

  loadReactive(): Observable<boolean> {
    return this.http.get<ResultData>(this.URL)
      .pipe(
        map((data: ResultData) => {
          this.reactiveResult = data.title;
          return true;
        }));
  }

Enter fullscreen mode Exit fullscreen mode

In the component, I can just subscribe to the change:

  onLoadReactive() {
    this.store.loadReactive()
      .subscribe(s => console.log("Success"),
        e => console.log("Failure"));
  }

Enter fullscreen mode Exit fullscreen mode

All the nesting makes this hard to read in my opinion. I am thinking of showing the async/await pattern instead. Here would be the call in the service:

  async loadAsync(): Promise<boolean> {

    const result = await this.http.get<ResultData>(this.URL)
      .toPromise();

    this.asyncResult = result.title;

    return true;
  }

Enter fullscreen mode Exit fullscreen mode

Longer but clearer I think. And in the component:

  async onLoadAsync() {
    try {
      if (await this.store.loadAsync()) {
        console.log("Sucess");
      } else {
        console.log("Failure")
      }
    } catch {
      console.log("Failure")
    }
  }

Enter fullscreen mode Exit fullscreen mode

I plan on teaching both, but is Angular moving away from the subscribe model to async/await now that it exists or are people sticking with it?

Please help me tell the right story to new Angular users!

Creative Commons License

This work by Shawn Wildermuth is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.

Based on a work at wildermuth.com.


If you liked this article, see Shawn's courses on Pluralsight.

Top comments (0)