首页 > 解决方案 > 角度不显示对象属性

问题描述

我正在关注HeroTutorial但使用的是 Django 后端。我有一个Hero从 DRF 端点获取的对象(通过 Postman 验证)。在我的hero-detail.htmlhero.namehero.id没有显示任何内容。

我知道该hero对象正在传递给hero-detail.html,因为浏览器显示“详细信息”和“id:”所以该行<div *ngIf="hero">告诉我有一个hero..

但是如果有一个hero为什么hero.name什么都不显示呢?

浏览器控制台中没有错误。到hero-detail.component的链接来自dashboard.component,它使用相同的方法,但由于某种原因hero.name并且hero.number工作正常。dashboard.component.html显示正确,所以我知道我的服务运行良好。

我的hero-detail.html

<div *ngIf="hero">

<h2>{{hero.name | uppercase}} Details</h2>
<div><span>id: </span>{{hero.number}}</div>
<div>
  <label>name:
    <input [(ngModel)]="hero.name" placeholder="name">
  </label>
</div>

</div>

<button (click)="goBack()">go back</button>

hero-detail.component

import { Component, OnInit, Input } from '@angular/core';
import { Hero } from '../hero'
import { ActivatedRoute } from '@angular/router';
import { Location } from '@angular/common';
import { HeroService }  from '../hero.service';

@Component({
  selector: 'app-hero-detail',
  templateUrl: './hero-detail.component.html',
  styleUrls: ['./hero-detail.component.scss']
})
export class HeroDetailComponent implements OnInit {


  constructor(
  private route: ActivatedRoute,
  private heroService: HeroService,
  private location: Location
) {}

  @Input() hero: Hero;

  ngOnInit(): void {
    this.getHero();
  }

  getHero(): void {
    const number = +this.route.snapshot.paramMap.get('number');
    this.heroService.getHero(number)
      .subscribe(hero => this.hero = hero);
  }

  goBack(): void {
  this.location.back();
}

  }

仪表板.组件

import { Component, OnInit } from '@angular/core';
import { Hero } from '../hero';
import { HeroService } from '../hero.service';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: [ './dashboard.component.scss' ]
})
export class DashboardComponent implements OnInit {

  heroes: Hero[] = [];

  constructor(private heroService: HeroService) { }

  ngOnInit() {
    this.getHeroes();
  }

  getHeroes(): void {
    this.heroService.getHeroes()
      .subscribe(heroes => this.heroes = heroes.slice(1, 5));
  }
}

仪表板.html

<h3>Top Heroes</h3>
<div class="grid grid-pad">
  <a *ngFor="let hero of heroes" class="col-1-4"
      routerLink="/detail/{{hero.number}}">
    <div class="module hero">
      <h1>{{hero.name}}</h1>
    </div>
  </a>
</div>

英雄服务

import { Injectable } from '@angular/core';
import { Hero } from './hero';
import { HEROES } from './mock-heroes';
import { Observable, of } from 'rxjs'
import { HttpClient, HttpHeaders } from '@angular/common/http'
import { catchError, map, tap } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})


export class HeroService {

private heroesUrl = 'http://127.0.0.1:8000/heroes/';  // URL to web api

  constructor(
  private http : HttpClient
) { }

  /**
 * Handle Http operation that failed.
 * Let the app continue.
 * @param operation - name of the operation that failed
 * @param result - optional value to return as the observable result
 */

  getHeroes (): Observable<Hero[]> {
  return this.http.get<Hero[]>(this.heroesUrl)

}

  getHero(number:number): Observable<Hero>{
    return this.http.get<Hero>(`${this.heroesUrl}${number}`);
  }

//  getHero(number: number): Observable<Hero> {
//  return of(HEROES.find(hero => hero.number === number));
//}


}

来自 Postman 的hero.service端点响应localhost:8000/heroes/2

[
    {
        "name": "better hero",
        "number": 2
    }
]

还有来自 Postman 的hero.service端点响应localhost:8000/heroes

[
    {
        "name": "bad hero",
        "number": 7
    },
    {
        "name": "bad hero",
        "number": 7
    },
    {
        "name": "better hero",
        "number": 2
    }
]

视图.py

class HeroList(generics.ListAPIView):
    queryset = Hero.objects.all()
    serializer_class = HeroSerializer

    class Meta:
        model = Hero
        fields = ('number', 'name')


class HeroDetail(generics.GenericAPIView):
    serializer_class = HeroSerializer

 #TODO why do i need many=True here, this should returning one instance
    def get(self, request, number):
        # number = self.request.query_params.get('number')
        hero_detail = Hero.objects.filter(number=number)
        serializer = HeroSerializer(hero_detail, many=True)
        return Response(serializer.data)

    class Meta:
        model = Hero
        fields = ('number', 'name')

标签: djangoangulardjango-rest-framework

解决方案


查看您发布的示例 API 响应,看起来英雄的检索方法(例如 /heroes/2)返回一个只有一个项目的列表,而不是返回项目本身。但是,在您的客户端代码中,您需要一个英雄对象,而不是英雄列表。根据您的客户端代码和一般的休息 api,

localhost:8000/heroes/2 应该返回

{
    "name": "better hero",
    "number": 2
}

不是

[
    {
        "name": "better hero",
        "number": 2
    }
]

推荐阅读