Как получить favRecipes от пользователя, а затем отобразить его в Angular - PullRequest
0 голосов
/ 16 марта 2020

Я пытаюсь отобразить любимые рецепты текущего зарегистрированного пользователя. У меня проблемы с получением данных.

Проект находится в ASP. NET Core MVC и Angular.

На моей вкладке сети я вижу это:

enter image description here

У меня пропущены поля: RecipePhotos и User.

Я не понимаю этого, потому что когда я получаю данные из API в Почтальон, вроде бы хорошо:

enter image description here

Мой код:

Resolver

@Injectable()
    export class FavRecipesResolver implements Resolve<Recipe[]> {

        constructor(private userService: UserService, private router: Router, private alertify: AlertifyService) {

        }

        resolve(route: ActivatedRouteSnapshot): Observable<Recipe[]> {
            return this.userService.getFavRecipes(route.params.id).pipe(
                catchError(error => {
                    this.alertify.error('Problem retrieving data');
                    this.router.navigate(['/home']);
                    return of(null);
                })
            );
        }
    }

Компонент

@Component({
      // tslint:disable-next-line: component-selector
      selector: 'app-favRecipe-lists',
      templateUrl: './favRecipe-lists.component.html',
      styleUrls: ['./favRecipe-lists.component.css']
    })
    export class FavRecipeListsComponent implements OnInit {
      recipes: Recipe[];

      constructor(private authService: AuthService, private userService: UserService,
                  private route: ActivatedRoute, private alertify: AlertifyService) { }

      ngOnInit() {
        this.route.data.subscribe(data => {
          this.recipes = data.recipes.result;
        });
      }

В моем route.ts

{path: 'my-fav-recipes', component: FavRecipeListsComponent, resolve: {recipes: FavRecipesResolver}},

в моем userService

getFavRecipes(id: number) {
    return this.http.get(this.baseUrl + 'users/' + id + '/favouriteRecipes');
  }

Модели:

export interface User {
    id: number;
    username: string;
    knownAs: string;
    age: number;
    gender: string;
    created: Date;
    lastActive: Date;
    photoUrl: string;
    city: string;
    country: string;
    introduction?: string;
    userPhotos?: UserPhoto[];
    recipes?: Recipe[];
}


export interface Recipe {
    id: number;
    name: string;
    ingredients: string;
    preparationTime: number;
    dateAdded: Date;
    photoUrl: string;
    description?: string;
    recipePhotos?: RecipePhoto[];
}

Что я делаю не так ?

Это правильный подход? Или, может быть, я должен создать FavouriteRecipe модель, как у меня в C#?

@ EDIT

@ bjdose

enter image description here

ответ favRecipes enter image description here

Фото не отображается

enter image description here

В моем html

favRecipe-lists. html

<div class="row recipes-body">
    <div *ngFor="let recipe of recipe" class="col-md-4 col-sm-6 mb-4">
      <app-recipes-card [recipe]="recipe"></app-recipes-card>
    </div>
  </div>

fav-recipe-card. html

<div class="card text-white">
  <div class="card-img-wrapper">
    <img class="card-img"  src="{{recipe.recipePhotos[0].url|| '../../../../../../assets/image.png'}}" alt="{{recipe.name}}">
      <div class="card-img-overlay d-flex flex-column p-0">

        <div class="d-flex flex-column text-center  mb-3 mt-4">
          <h4 class="card-text-name bg-opacity text-white">{{recipe.name}}</h4>
        </div>
        <div class=" d-flex mt-auto">
            <h4 class="card-text text-white  p-2 mb-0">{{recipe.dateAdded}}</h4>
            <h4 class="card-text  text-white p-2 ml-auto">{{recipe.preparationTime}} <i class="fa fa-clock-o"></i></h4>
            <ul class="list-inline recipe-icons animate text-center">
              <li class="list-inline-item"><h2 class="text-white mr-5" (click)="addToFav(recipe.id)"><i class="fa fa-heart"></i></h2></li>
              <li class="list-inline-item"><h2 class="text-white mr-5"><i class="fa fa-comment"></i></h2></li>
              <li class="list-inline-item"><h2 class="text-white"><i class="fa fa-eye" [routerLink]="['/recipes/', recipe.id]"></i></h2></li>
            </ul>

        </div>
      </div>
</div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...