简体   繁体   中英

Best practice of Angular

I've just finished my Angular lessons and I already find out some differences between what I learn and the Angular official documentation.

Let's imagine I want to recover an user with ID of an API.

Here is how I would do it according to my lessons :

export class UserService {

  constructor(
    private httpClient: HttpClient
  ) {
  }

  public user: User; // local variable using User model
  public userSubject: BehaviorSubject<User> = new BehaviorSubject<User>(null);

  async getSingleUserFromServer() {
    await this.httpClient.get<any>('https://xvalor.repliqa.fr/api/v1/user/' + this.userId).subscribe(
      (response) => {
        this.user = response;
        this.userPortfolios = this.user.portfolioAssoc;
        this.emitSubjects();
      });
  }

  emitSubjects() {
    this.userSubject.next(this.user);
  }
}

and here is how angular doc procceed

getHeroes (): Observable<Hero[]> {
  return this.http.get<Hero[]>(this.heroesUrl)
    .pipe(
      tap(_ => this.log('fetched heroes')),
      catchError(this.handleError<Hero[]>('getHeroes', []))
    );
}

I understand than both methods are quiet doing the same thing, I just want to be sure which one I should use, especially in big project developpement.

I would stick to the second approach as it is more generic and it uses Observable . Observale allow to emit any count of events and callback will be called for each event. Promise generates a single event after completion.

In addition, service class should not have async and await parts. The goal of service is to return data and UI component can consume data using async and await parts. async and await are syntactic sugar to avoid writing .subscribe part as it is really verbose. So write async and await in your UI components.

If you want to use Promise , then your service should not have subscribe part:

getSingleUserFromServer() {
    return this.httpClient.get<any>('https://xvalor.repliqa.fr/api/v1/user/' + this.userId);
}

However, it is better to return Observables from your service.

Your first approach is flawed in that the consumer must perform two separate operations: call getSingleUserFromServer() to make the call, and subscribe to UserService.user to consume the results. And in case of errors, he won't receive any feedback.

Stick to the official guidelines for now. BTW, if your goal was to additionally store the user as a variable available to everyone, then with the Observable pattern it's as simple as adding another tap to the pipe:

httpClient.get(url)
    .pipe(
        someOperator(),
        tap(user => this.user = user),
        anotherOperator(...someArgs),
    )

Observables and Subjects are two diffrent objects from rxjs and bring diffrent properties with them. The answers to this question show some of the key differences: What is the difference between a Observable and a Subject in rxjs?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM