简体   繁体   English

Angular 最佳实践

[英]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.我刚刚完成了我的 Angular 课程,我已经发现我所学的内容与 Angular 官方文档之间的一些差异。

Let's imagine I want to recover an user with ID of an API.让我们想象一下,我想用 API 的 ID 恢复一个用户。

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 .我会坚持第二种方法,因为它更通用并且它使用Observable Observale allow to emit any count of events and callback will be called for each event. Observale 允许发出任何数量的事件,并且将为每个事件调用回调。 Promise generates a single event after completion. Promise 在完成后生成单个事件。

In addition, service class should not have async and await parts.此外,服务类不应有asyncawait部分。 The goal of service is to return data and UI component can consume data using async and await parts. service 的目标是返回数据,UI 组件可以使用asyncawait部分来消费数据。 async and await are syntactic sugar to avoid writing .subscribe part as it is really verbose. asyncawait是避免编写.subscribe部分的语法糖,因为它非常冗长。 So write async and await in your UI components.所以在你的 UI 组件中编写asyncawait

If you want to use Promise , then your service should not have subscribe part:如果你想使用Promise ,那么你的服务不应该有subscribe部分:

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.但是,最好从您的服务中返回Observables

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.您的第一种方法有缺陷,因为使用者必须执行两个单独的操作:调用getSingleUserFromServer()进行调用,订阅UserService.user以使用结果。 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:顺便说一句,如果您的目标是另外将用户存储为每个人都可以使用的变量,那么使用 Observable 模式就像在管道中添加另一个tap一样简单:

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. Observables 和 Subjects 是两个与 rxjs 不同的对象,它们带来了不同的属性。 The answers to this question show some of the key differences: What is the difference between a Observable and a Subject in rxjs?这个问题的答案显示了一些关键差异: rxjs 中的 Observable 和 Subject 之间有什么区别?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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