angular - 关于 observable 的最佳实践

标签 angular observable

我有一个工作代码,但它并不是根据响应式(Reactive)编程规范以最佳方式编写的。

正如您在代码中看到的,我需要使用可观察对象返回给我的数据。

不要过多考虑 for 循环的作用,我只需要使用可观察返回给我的数据。

如果我在订阅之外运行 for 循环,则可能我需要的数据尚不可用,因此我无法遵循此路径。

ngOnInit(): void {

    this.subscriptionGetRating = this.ratingService.getRating(this.userId).subscribe({ 

      next:data => {

        this.count = data['count'];
        this.rating = data['rating'] / this.count;

        if(this.count == 0){

          this.rating = 0;

          for(let k=0;k<=4;k++){
            this.ratingArray[k] = this.greyStar;
          }

        } else{

          let trunc = Math.trunc(this.rating);

          for(let j=0;j<trunc+1;j++){

            if(this.rating>j && this.rating<j+1){
              this.ratingArray[j] = this.midStar;
            }else {
              if(j!=trunc)
                this.ratingArray[j] = this.yellowStar;
            }

          }

          if (this.rating == Math.floor(this.rating)){
            for(let k=trunc;k<=4;k++){
              this.ratingArray[k] = this.greyStar;
            }
          } else {
            for(let k=trunc+1;k<=4;k++){
              this.ratingArray[k] = this.greyStar;
            }
          }

        }

      },

      error:error => {
        console.error(error);
      }

    });

}

我希望有好心人至少能给我一个例子来说明如何解决这个问题。

在网上阅读时,我只找到了一些示例,其中执行的唯一操作是在控制台中打印可观察值返回的数据(console.log(data);)。

最佳答案

1: this.RatingService.getRating(this.userId).pipe( map ( 数据=> { 在这里处理数据 }));

2:尽量减少在 TS 文件中使用订阅,使用管道(map())将其返回可观察

2.1:尝试读取 rxjs 库中不同类型的 map https://blog.angular-university.io/rxjs-higher-order-mapping/

3:如果你想在 html 文件中使用可观察的使用异步管道

4:如果您使用订阅,请务必在 ngondestroy 中取消订阅。

关于angular - 关于 observable 的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60415121/

相关文章:

java - RxJava2 observable take 抛出 UndeliverableException

d3.js - d3js 中矩形的大小基于值的总和而不是项目的数量

html - MySQL 到 InnerHtml Angular 7

javascript - 处理管道和订阅 firebase Query 对象的类似方法是什么?

angular - 从 Angular 6 迁移到 Angular 7

Angular 2+ : Trigger an observable externally

javascript - 发出第一个值然后忽略计时器内发出的值

javascript - 如何 "combine"3 个或更多 Observables?

Angular 2 - 如何在 app.component 中有一个 `svg` 和一个 `circle` 作为子组件?

javascript - 在 Angular 2/typescript 中声明 javascript 方法以避免属性 x 不存在错误