471079 (1) [Avatar] Offline
#1
Hi

I am reading chapter 10 and is curious of why you have chosen to return Promise<> from the functions in loc8r-data.service.ts. Similar functionality is implemented returning Observables<> in the Hero Tutorial available on https://angular.io/tutorial/toh-pt6. What are the motivations behind returning Promise?

From Getting MEAN:
  
  public addReviewByLocationId(locationId: string, formData: any): Promise<any> {
    const url = `${this.apiBaseUrl}/locations/${locationId}/reviews`;
    return this.http
      .post(url, formData)
      .toPromise()
      .then(response => response.json() as any)
      .catch(this.handleError);
  }



From angular.io:
  
  addHero(hero: Hero): Observable<Hero> {
    return this.http.post<Hero>(this.heroesUrl, hero, httpOptions).pipe(
      tap((_hero: Hero) => this.log(`added hero w/ id=${_hero.id}`)),
      catchError(this.handleError<Hero>('addHero'))
    );
  }


Thanks!
Jumy Elerossë (11) [Avatar] Offline
#2
I think he did it because it was easier to understand how promise (single event) works, and then use that knowledge to move to into use of observables (Stream).
331872 (131) [Avatar] Offline
#3
Hello, I'm Luis, the editor of the book. I'll do my best to answer the question.

It could absolutely be a teaching approach. It's definitely recommended to understand how Promises work before understanding Observables. This could have been the motivation.

The fact is that both work just as well, it really depends on how much processing you need to apply to the eventual result. If you're fetching data remotely and then need to apply some basic operations on that data before rendering it to the client, then Promises work perfectly well; there's no need for the extra power that Observables bring. If the data in its raw form brought from the server needs much more, or possibly make additional server requests stemming from the original one, then you could use Observables and its rich API to massage that data more and mash it up to what you need.

Even the example that you cited from the angular.io page, to me, is a bad example of using Observables. That example is using Observables to pipe a tap(console.log) with a catch(), both of which are nicely captured in a promise by a .then then a .catch. So absolutely I see no need to use Observables for this example in chapter 8, nor the example is shown in angular.io--I think they just did that for illustration purposes. In this case, Observables is overkill.

I think the main goal is to understand the MEAN stack, primarily. It could be a good idea to bring in some discussion about RxJS in this book to create awareness, and then point to some additional references (RxJS in Action, for instance) because it's not a very simple topic to cover in just a page or two.

Good question. If you have any additional questions, don't hesitate to ask. Thanks!