Я следую курсу Angular, но в видео используется класс разрешения, который сейчас устарел и недоступен в Angular 17. Я просмотрел несколько разных статей, но не могу заставить его возвращать данные в качестве курса. ожидает.
Ниже приведен код из класса
введите сюда описание изображения
Я пытался следовать другим статьям и изменить его с класса на константу, но мне не удалось понять, как вернуть вызов метода выборки рецептов.
Ниже приведен модифицированный код:
import { Recipe } from "./recipe.model";
import { DataStorageService } from "../shared/data-storage.service";
@Injectable({providedIn: 'root'})
export const RecipesResolverService: ResolveFn<Recipe[]> =
(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => {
const dataStorageService = inject(DataStorageService);
return this.dataStorageService.fetchRecipes();
}
Ниже приведен файл data-storage.service.ts, о котором говорилось выше:
import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { map, tap } from "rxjs/operators";
import { Recipe } from "../recipes/recipe.model";
import { RecipeService } from "../recipes/recipe.service";
@Injectable({ providedIn: 'root' })
export class DataStorageService {
constructor(private http: HttpClient, private recipesService: RecipeService) { }
storeRecipes() {
const recipes = this.recipesService.getRecipes();
this.http.put(
'https://ng-course-recipe-book-af2f9-default-rtdb.firebaseio.com/recipes.json',
recipes
)
.subscribe(response => {
console.info(response);
});
}
fetchRecipes() {
return this.http
.get<Recipe[]>(
'https://ng-course-recipe-book-af2f9-default-rtdb.firebaseio.com/recipes.json'
)
.pipe(
map(recipes => {
return recipes.map(recipe => {
return {
...recipe,
ingredients: recipe.ingredients ? recipe.ingredients : []
};
});
}),
tap(recipes => {
this.recipesService.setRecipes(recipes);
})
)
}
}
Ниже приведен файл app-routing.module.ts с разрешением, используемым в компонентах RecipeDetail и Edit:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { RecipesComponent } from './recipes/recipes.component';
import { ShoppingListComponent } from './shopping-list/shopping-list.component';
import { RecipeStartComponent } from './recipes/recipe-start/recipe-start.component';
import { RecipeDetailComponent } from './recipes/recipe-detail/recipe-detail.component';
import { RecipeEditComponent } from './recipes/recipe-edit/recipe-edit.component';
import { RecipesResolverService } from './recipes/recipes-resolver.service';
const appRoutes: Routes = [
{path: '', redirectTo: '/recipes', pathMatch: 'full'},
{ path: 'recipes', component: RecipesComponent, children: [
{ path: '', component: RecipeStartComponent},
{ path: 'new', component: RecipeEditComponent},
{ path: ':id', component: RecipeDetailComponent, resolve: [RecipesResolverService]},
{ path: ':id/edit', component: RecipeEditComponent, resolve: [RecipesResolverService]}
]},
{ path: 'shopping-list', component: ShoppingListComponent},
];
@NgModule({
imports: [RouterModule.forRoot(appRoutes)],
exports: [RouterModule]
})
export class AppRoutingModule {
}
Пожалуйста, дайте мне знать, что я делаю неправильно. Кажется, что все статьи, которые я просмотрел, используют разные подходы. Ниже приведены ссылки на те немногие, которые я смотрел:
https://medium.com/codex/functional-resolvers-in-angular-43951c50c4ehttps://blog.bitsrc.io/how-ive-replaced-deprecated-resolvers-in-angular-16-59811f79cd5bhttps://angularjobs.com/curated/how-ive-replaced-deprecated-resolvers-in-angular-16-59811f79cd5b-on-blog-bitsrc-io





Ниже приведен список изменений, которые необходимо сделать.
При работе сsolverFn вам не нужен @Injectable(...), поскольку он предназначен только для сервиса, а не для функции:
import { Recipe } from "./recipe.model";
import { DataStorageService } from "../shared/data-storage.service";
export const RecipesResolverService: ResolveFn<Recipe[]> = (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => {
const dataStorageService = inject(DataStorageService);
return this.dataStorageService.fetchRecipes();
}
Затем вы можете попробовать импортировать преобразователь как свойство объекта:
...
{ path: ':id', component: RecipeDetailComponent, resolve: { data: RecipesResolverFn } },
{ path: ':id/edit', component: RecipeEditComponent, resolve: { data: RecipesResolverFn } }
...
Затем мы можем подписаться на получение данных:
...
constructor(private activatedRoute: ActivatedRoute) { }
ngOnInit() {
this.activatedRoute.data.pipe(map(data => data['data'])).subscribe((response: any) => {
// use the data
});
...
Спасибо, это очень помогло! Единственное, что мне нужно было изменить в дополнение к вашим комментариям, это: return this.dataStorageService.fetchRecipes(); ---> вернуть dataStorageService.fetchRecipes(); Ваше здоровье!