Rants and Raves

Thanks for visiting my blog!

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

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;
        }));
  }

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

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

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;
  }

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")
    }
  }

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!