我目前正在学习ANGLING,并在学习马克西米安·施瓦茨米勒·乌德米课程.
我有一个简单的CRUD应用程序来管理食谱,数据保存在数据库中,我希望能够通过发送一个HTTP请求来删除、创建和更新食谱,然后相应地更新食谱列表.
仅使用RxJS BehaviorSubject和一个服务,我目前就有这个删除食谱的实现:
export class RecipeDetailComponent implements OnInit {
selectedRecipe: Recipe;
constructor(
private recipeService: RecipeService,
private activatedRoute: ActivatedRoute,
private router: Router
) { }
ngOnInit() {
this.activatedRoute.params.subscribe((params) => {
const id = params.id;
this.recipeService.getRecipeById(id).subscribe((recipe) => {
this.selectedRecipe = recipe;
});
});
}
onDeleteRecipe() {
this.recipeService.deleteRecipe(this.selectedRecipe.id).subscribe({
next: () => {
this.router.navigate(['/recipes']);
this.recipeService.recipesUpdate.next();
},
error: (error) => {
console.error('error deleting recipe : ', error);
}
});
}
}
export class RecipeListComponent implements OnInit {
recipes$: Observable<Recipe[]>;
isLoading = false;
errorMessage: string;
constructor(private recipeService: RecipeService) {}
ngOnInit() {
this.initRecipes();
this.recipeService.recipesUpdate.subscribe(() => this.initRecipes());
}
initRecipes() {
this.isLoading = true;
this.recipes$ = this.recipeService.getRecipes().pipe(
catchError((error) => {
console.error('error retrieving recipes : ', error);
this.errorMessage = `Error retrieving recipes : ${error.error.error}`;
return of([]);
}),
tap({ complete: () => (this.isLoading = false) })
);
}
}
export class RecipeService {
API_URL =
'XXX';
private recipes: Recipe[] = [];
recipesUpdate: Subject<void> = new Subject<void>();
recipes$ = new BehaviorSubject<Recipe[]>(this.recipes);
constructor(private http: HttpClient) { }
getRecipes() {
return this.http.get<Recipe[]>(`${this.API_URL}/recipes.json`)
}
getRecipeById(id: string) {
return this.http.get<Recipe>(`${this.API_URL}/recipes/${id}.json`)
}
addRecipe(recipe: Recipe) {
return this.http
.post(`${this.API_URL}/recipes.json`, recipe)
.subscribe((response) => {
this.recipesUpdate.next();
});
}
updateRecipe(recipe: Recipe) {
return this.http
.put(`${this.API_URL}/recipes/${recipe.id}.json`, recipe)
.subscribe((response) => {
this.recipesUpdate.next();
});
}
deleteRecipe(id: string) {
return this.http.delete(`${this.API_URL}/recipes/${id}.json`);
}
}
我不确定这是否是最好的方法,尤其是我使用空主题更新RecipeListComponent中的食谱列表并在ngOnInit方法中订阅它的方式.
我读了很多关于NgRx的 comments ,以及它对于简单的应用程序(https://blog.angular-university.io/angular-2-redux-ngrx-rxjs/)来说通常被认为是过度杀伤力,但我不确定如何在不使用它的情况下做到这一点.
此外,我不喜欢在删除、创建或更新食谱之后必须"重新加载"食谱列表并显示加载程序的事实.为此,我使用了Reaction Query和Reaction.有没有办法用Angular 来达到同样的效果?
prize 问题: 关于NgRx,在我的转角过程中,我几乎到了关于NgRx的部分,但我不确定我是否应该跟随它.你认为它值得学习吗?