Angular: 如何处理 Observables 并在不同的方法中使用结果

Angular: how to handle Observables and use result in different methods

我很难理解应该如何使用 Observables 来满足我的要求。例如,假设我有一个应用程序并且为了国际化,我正在使用带有所有标签和翻译的 REST 服务。一些标签可以根据页面上执行的操作而改变。而且我不确定如何从服务中检索数据并以不同的方法使用它。

让我们看看这个伪代码:

labels: KeyValuePair[];
userDetails: UserDetails;
displayedColumns: string[];

// services below generated thanks to ng-swagger-gen
constructor(
   labelService: LabelService, 
   userService: UserService
){}

ngOnInit() {
   this.userService.get().subscribe(
      (userData) => {
        this.userDetails = userData; 
        console.log(userData);
      },
      (error) => {
        this.errorMessage = error;
      }
    );

   this.labelService.get(this.userDetails.getLanguage()).subscribe(
      (labelsResponse) => {
        this.labels = labelsResponse; // use the labels in HTML template
        console.log(labelsResponse);
      },
      (error) => {
        this.errorMessage = error;
      }
    );

   this.retrieveTableColumns();
}

retrieveTableColumns() {
   this.displayedColumns = this.labels.filter(/* filter columns */);
}

executeMethods() { // method executed from HTML template
   this.doSomethingWithUserDetails();
   this.doSomethingWithLabels();
}

doSomethingWithUserDetails() {
   // 1. do differnet things and use it in HTML template
   // 2. check one of properties and based on this 
   this.setColumns();
}

setColumns() { // columns used in mat-table
    if (this.userDetails.allowedForAction) {
        this.displayedColumns = this.columnsDef.concat(['action']);
        this.hiddenColumns.push(this.displayedColumns.length);
    } else {
        this.displayedColumns = this.columnsDef;
    }
}

doSomethingWithLabels() {
   // do some magic using retrieved labels
}

为了生成 Web 客户端服务,我使用了 ng-swagger-gen

如何处理 Observables 来实现这个?因此能够在不同的地方使用数据。我听说过用 .toPromise 转换它并使用 async await,但我也听说这是反模式......所以不确定在这里做什么......我正在使用 Angular 9 如果重要的话。

基础知识

您只需将响应保持为可观察的:

labels$ = this.labelService.get(this.userDetails.getLanguage())

并且在 Html 中使用异步管道:

*ngFor="let label of labels$ | async"

如果你想转换打字稿中的数据,你可以在可观察对象上使用'.pipe()'并创建一个新的:

newLabels$ = labels$.pipe(
    map(labels => labels.filter(label => label.id > 5)),
    // Or whatever you want to filter, sorry no inspiration
    tap(labels => console.log(labels)),
    // more pipes ...
)

您可以创建自己的函数以在这些管道中使用。

您也可以编写一个函数,将可观察对象中的任何对象作为参数,然后在您的 html:

中使用该函数
*ngFor="let label of labelsSortedByName((labels$ | async)!)"

我使用 ngFor 作为示例,因为它被广泛使用,但您可以在任何地方使用它。基本上尝试不订阅你的代码,只使用异步管道。学习高阶可观察量,将多个可观察量组合在一起,您将获得很多乐趣。

合并 Observables

示例:

first$ = of("en") // An observable representing the result of your first request

second(lang: string): Observable<string> { // Request requiring a string argument
  return of(lang + " language")
}

result$ = this.first$.pipe( // The resulting observable of the second request
  mergeMap(r => {
    return this.second(r)
  })
)

在模板中:

{{ result$ | async }}  <!-- Result: 'en language' -->

在此示例中,first$second() 只是对您的请求的模拟。我意识到你的第二个请求除了连接字符串之外还做了其他事情,但想法是一样的。它接受第一个 Observable 持有的类型的参数,并返回一个新的 Observable。

这里有一个 Stackblitz 给你玩。