Проблема с изменением класса Resolve на ResolveFn для курса Angular

Я следую курсу 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

Тестирование функциональных ngrx-эффектов в Angular 16 с помощью Jest
В системе управления состояниями ngrx, совместимой с Angular 16, появились функциональные эффекты. Это здорово и делает код определенно легче для...
Angular и React для вашего проекта веб-разработки?
Angular и React для вашего проекта веб-разработки?
Когда дело доходит до веб-разработки, выбор правильного front-end фреймворка имеет решающее значение. Angular и React - два самых популярных...
Эпизод 23/17: Twitter Space о будущем Angular, Tiny Conf
Эпизод 23/17: Twitter Space о будущем Angular, Tiny Conf
Мы провели Twitter Space, обсудив несколько проблем, связанных с последними дополнениями в Angular. Также прошла Angular Tiny Conf с 25 докладами.
Угловой продивер
Угловой продивер
Оригинал этой статьи на турецком языке. ChatGPT используется только для перевода на английский язык.
Мое недавнее углубление в Angular
Мое недавнее углубление в Angular
Недавно я провел некоторое время, изучая фреймворк Angular, и я хотел поделиться своим опытом со всеми вами. Как человек, который любит глубоко...
Освоение Observables и Subjects в Rxjs:
Освоение Observables и Subjects в Rxjs:
Давайте начнем с основ и постепенно перейдем к более продвинутым концепциям в RxJS в Angular
2
0
60
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Ниже приведен список изменений, которые необходимо сделать.

При работе с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(); Ваше здоровье!

Miles Winokur 17.06.2024 05:36

Другие вопросы по теме