[英]best pratice about observable
我有一個工作代碼,但根據反應式編程的規范,它不是以最佳方式編寫的。
正如你在代碼中看到的,我需要使用 observable 返回給我的數據。
不要過多考慮for循環的作用,我只需要使用observable返回給我的數據。
如果我在訂閱之外運行 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( data => { HANDLE DATA HERE }));
2:盡量減少在 TS 文件中使用 Subscription 使用 A pipe(map()) 返回它 observable
2.1:嘗試閱讀 rxjs 庫中不同類型的地圖https://blog.angular-university.io/rxjs-higher-order-mapping/
3:如果你想在 html 文件中使用可觀察的使用異步管道
4:如果您使用訂閱,請始終在 ngondestroy 中取消訂閱。
我認為您正在尋找這種訂單:
this.obs.subscribe(
val => { console.log(val) }, //next callback
error => { console.log("error") }, //error callback
() => { console.log("Completed") } //complete callback
)
好的,所以你說你需要在 observable 中做一個 for 循環,問題是為什么?,但如果你必須這樣做。 您可以使用運算符管道,然后映射項目以執行以下代碼:
iAmAnObservable .pipe( map(value => value.item),//--> for 迭代observable 中的值,幫助你處理數據的變化。take(1),//--> 用於使用部分數組中只有 takeUntil(this._destroyed$) );
但是說真的,這不是一個好的做法,在組件中使用邏輯,實際上在前端,您需要嘗試在后端完成所有操作並將結果注入到 angular 應用程序中,如果您也想查看最佳實踐對於 angular,我推薦這個鏈接: https : //www.freecodecamp.org/news/best-practices-for-a-clean-and-performant-angular-application-288e7b39eb6f/
為了獲得更清晰和可紅的代碼,您可以使用以下代碼(我假設 getRating 發送一個請求,您需要等待響應)
try {
let data = await this.ratingService.getRating(this.userId).toPromise();
// here process data using if/for
} catch(e) {
// handle error here
}
不要忘記在ngOnInit()
之前添加關鍵字async
。 如果您不想處理錯誤,則刪除 try-catch - 那么您的代碼會更簡單(更少嵌套)。 Async/await 構造旨在消除異步代碼的復雜性(嵌套)。 使用它你的代碼看起來更像典型的同步代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.