繁体   English   中英

Angular 如何显示来自用户的包含数组的数据

[英]Angular how to display data from user which contain an array

我正在研究 RecipesApp(Asp.Net MVC + Angular as a View)

我有包含食谱 ICollection 的用户

我想要做的是:

显示来自用户的所有食谱。

像那样 *ngFor 让 user.recipes 的用户

{{user.recipes}}

我已经尝试过的我的用户类:

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 class MemberDetailComponent implements OnInit {
  user: User;
  recipes: Recipe[];

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

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

html

<div class="container">
    {{user.username}}
    <br>
    <hr>
    <p class="text-center">User Recipes: </p>

    <!-- <div *ngFor="let user of user" class="col-lg-3 col-md-3 col-sm-6">
      </div> -->
    </div>

@编辑

我的解析器:

import {Injectable} from '@angular/core';
import { User } from '../_models/user';
import { Resolve, Router, ActivatedRouteSnapshot } from '@angular/router';
import { UserService } from '../_services/user.service';
import { Observable, of } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { AlertifyService } from '../_services/alertify.service';


@Injectable()
export class MemberDetailResolver implements Resolve<User> {

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

    }

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

    }
}

食谱类

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

在你的 .html 中试试这个:

在您的 ts 中,您需要执行以下操作:

ngOnInit() {
    this.route.data.subscribe(data => {
      this.user= data.user; //here change
    });
  }

并在您的 html 中(我想 recipes 类有一个属性名称)

     <div  *ngFor="let recipe of user.recipes" >
      <p>{{recipe.name}}</p>
     </div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM