【问题标题】:angular save() method not working hero tutorial角度保存()方法不起作用英雄教程
【发布时间】:2019-04-13 16:29:47
【问题描述】:

遵循 Angular(使用 7.3.4)英雄教程。使用 Angular 和 django 后端。我似乎无法更新英雄名称:

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

我怀疑 heroService.updateHero 方法指向了错误的 url,但我不确定将其指向何处或将其传递给什么。同样在return this.http.put(this.heroesUrl, hero, httpOptions 中使用Pycharm 和put 作为未解决的函数是红色的,但我认为这只是一个无关紧要的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>

【问题讨论】:

  • 您从 put 请求中获得了什么回报?
  • 如果没有看到你的 django urls 文件就不能确定,但​​可能你应该将 put 请求发送到${this.heroesUrl}${hero.id}/
  • @OzgurAkcali 我实际上尝试过,但updateHero() 方法只传递了一个英雄而不是英雄ID,所以我尝试了${this.heroesUrl}${hero.id},这似乎有效,如果你发布一个答案我可以标记正确,谢谢!

标签: django angular django-rest-framework


【解决方案1】:

您应该将 put 请求发送到“/heroes/hero_id/”以获取更新。使用 RESTful API,一般来说,您应该发送

  • POST 请求到 /heroes/ -> 创建英雄
  • GET 请求到 /heroes/ -> 列出英雄
  • GET 请求到 /heroes/id/ -> 获取单个英雄
  • PUT 请求到 /heroes/id/ -> 更新英雄
  • 对 /heroes/id/ 的删除请求 -> 删除英雄

所以在你的例子中,你应该像这样修改你的 updateHero 方法:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-22
    • 2018-08-12
    • 2018-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多