angular save()方法不起作用英雄教程

时间:2019-04-13 16:29:47

标签: django angular django-rest-framework

遵循角度(使用7.3.4)英雄指南。在Django后端中使用angular。我似乎无法更新英雄名称:

我有一个 hero-detail.component.ts ,它具有一个save()方法,该方法应该通过hero方法来更新HeroService.updateHero()。当我单击“保存”按钮时,什么也没有发生...

我怀疑heroService.updateHero方法指向错误的url,但是我不确定将其指向何处或将其传递给什么。同样在put中使用Pycharm和return this.http.put(this.heroesUrl, hero, httpOptions也是红色,作为未解决的功能,但是我认为这只是Typescript Pycharm设置,应该无关紧要。

任何指针表示赞赏。

hero-detail.component.ts

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);
  }

  save(): void {
   this.heroService.updateHero(this.hero)
     .subscribe(() => this.goBack());
 }

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

hero.service.ts

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';

  const httpOptions = {
    headers: new HttpHeaders({ 'Content-Type': 'application/json' })
  };

@Injectable({
  providedIn: 'root'
})

export class HeroService {

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

  constructor(
  private http : HttpClient
) { }


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

}

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

  updateHero (hero: Hero): Observable<any> {
    return this.http.put(this.heroesUrl, hero, httpOptions)
  }

}


  }

heroes / views.py

from django.shortcuts import render
from rest_framework.response import Response

from .models import Hero
from rest_framework import generics
from .serializers import HeroSerializer
# Create your views here.


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

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


class HeroDetail(generics.GenericAPIView):
    serializer_class = HeroSerializer

    def get(self, request, id):
        hero_detail = Hero.objects.get(id=id)
        serializer = HeroSerializer(hero_detail)
        return Response(serializer.data)

    def put(self, request, id):
        hero_detail = Hero.objects.get(id=id)
        # hero_detail.name = request.data.get("name")
        hero_detail.save()
        serializer = HeroSerializer(hero_detail)
        return Response(serializer.data)



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

hero-detail.component.html

<div *ngIf="hero">

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

</div>

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

1 个答案:

答案 0 :(得分:0)

您应该将放置请求发送到“ / heroes / hero_id /”以进行更新。通常,使用Restful API,您应该发送

  • 向/ heroes /->创建英雄的POST请求
  • 获取对/ heroes /->列出英雄的请求
  • 获取对/ heroes / id /的请求->检索单个英雄
  • 向/ heroes / id /发送请求->更新英雄
  • 删除对/ heroes / id /的请求->删除英雄

因此,在您的示例中,您应该像这样修改updateHero方法:

updateHero (hero: Hero): Observable<any> {
    return this.http.put(`${this.heroesUrl}${hero.id}/` hero, httpOptions)
}