我有一个工作代码,但它并不是根据响应式(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/