我在浏览器中用一对输入从服务器中更改信息(服务器)。我想用两个按钮来决定是否用这些更改更新服务器。无法使saveChanges函数工作。
技能组件保存更改功能:
saveChanges(): void {
this.editMode = false;
this.skillsService.saveChanges(this.skills).subscribe();
}技能服务保存更改功能:
// Update changes made by the component
saveChanges(skills: SkillSet[]): Observable<SkillSet[]> {
console.log(skills); // Proof the array is returning with the edits.
return this.http.patch<SkillSet[]>(
this.skillsUrl,
skills,
this.httpOptions
);
}当使用按钮时,控制台响应修补程序http://localhost:5000/skills 404 (未找到),它也不适用于put。而url起作用,否则我模板一开始就得不到数据。网络/获取/XHR如果需要更多的信息,请告诉我。
-所有的密码--
SkillSet接口
export interface SkillSet {
id: number;
type: string;
title: string;
description: string;
tools: string[];
}技能构成部分(整个代码):
import { Component, OnInit } from '@angular/core';
import { SkillSet } from 'src/app/interfaces/skill-set';
import { SkillsService } from 'src/app/services/skills.service';
@Component({
selector: 'app-skills',
templateUrl: './skills.component.html',
styleUrls: ['./skills.component.scss'],
})
export class SkillsComponent implements OnInit {
login: boolean = true;
editMode: boolean = false;
skills: SkillSet[] = [];
newTool: string = '';
constructor(private skillsService: SkillsService) {}
ngOnInit(): void {
this.getSkills();
}
getSkills() {
this.skillsService
.getSkills()
.subscribe((skills) => (this.skills = skills));
}
// Edition functions of this section
addTool(skillSet: SkillSet, tool: string) {
if (tool) {
skillSet.tools.push(tool);
}
}
deleteTool(skillSet: SkillSet, tool: string) {
skillSet.tools = skillSet.tools.filter((t) => t !== tool);
}
// Changes menu
editStart() {
this.editMode = true;
console.log('Editing skills');
}
saveChanges(): void {
this.editMode = false;
this.skillsService.saveChanges(this.skills).subscribe();
}
cancelChanges() {
this.editMode = false;
this.getSkills();
}
}技能服务(整个代码):
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { SkillSet } from '../interfaces/skill-set';
@Injectable({
providedIn: 'root',
})
export class SkillsService {
private skillsUrl = 'http://localhost:5000/skills';
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
}),
};
constructor(private http: HttpClient) {}
getSkills(): Observable<SkillSet[]> {
return this.http.get<SkillSet[]>(this.skillsUrl);
}
// Update changes made by the component
saveChanges(skills: SkillSet[]): Observable<SkillSet[]> {
console.log(skills); // Proof the array is returning with the edits.
return this.http.patch<SkillSet[]>(
this.skillsUrl,
skills,
this.httpOptions
);
}
}发布于 2022-06-20 17:54:53
使用,每个http调用只能更新1项。通常您会像这样使用它:
http.patch(`{this.url}/{idToUpdate}`, bodyWithUpdate)如果该项是一个完整的结构,那么您可以更新完整的结构,但从外观上看,您没有这个结构。
要么更改json服务器返回的结构,要么在技能集中找到已更改的项并多次调用修补程序请求。
就像这样:
skills.forEach((skill)=>{
if (skill.changed){
http.patch(`{this.url}/{skill.id}`, skill);
}
})https://stackoverflow.com/questions/72690763
复制相似问题