我来自React,处于学习Angular的初期。我已经在Assets文件夹内创建了一个数据库,并已使用Httpclient成功完成了一个get请求。但是this.http.put(baseUrl,('item to beupdated'))失败了,我不明白angular如何识别数据库中要更新的项目。文档说angular会根据第二个参数的ID找到所需的商品?我希望对此进行澄清(如果您的数据库没有ID的话)。
第二,我的代码无法正常工作。我认为这是由于我对以上几点的误解,但下面的代码。我收到404未找到。
............................................... ...............................
service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Book } from '../models/book.interface';
@Injectable({ providedIn: 'root' })
export class BookService {
baseUrl = 'assets/db.json';
constructor(private http: HttpClient) {}
//this works!
getBooks(): Observable<any> {
return this.http.get<any>(this.baseUrl);
}
//this is failing!
haveRead(book: Book): Observable<any> {
return this.http.put(this.baseUrl, book);
}
}
............................................... ....................
component.ts
import { Component, OnInit, OnChanges, DoCheck } from '@angular/core';
import { Book } from '../models/book.interface';
import { BookService } from '../services/books.service';
@Component({
selector: 'app-to-read',
templateUrl: './to-read.component.html',
styleUrls: ['./to-read.component.css']
})
export class ToReadComponent implements OnInit {
books: Book[];
constructor(private bookService: BookService) {}
ngOnInit() {
this.getBooks();
}
getBooks(): void {
this.bookService.getBooks().subscribe(books => (this.books =
books.books));
}
//triggered via click handler
onReadIt(book): void {
book.haveRead = true;
this.bookService.haveRead(book).subscribe();
}
}
............................................... ............ 数据库的形状如下。
{
"books": [
{
"id": 1,
"title": "Harry Potter Series",
"description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
"review": 5,
"haveRead": true
},
.
.
.
{
"id": 8,
"title": "It",
"haveRead": false
}
]
}
提前感谢您的时间。
答案 0 :(得分:0)
通常HttpPut请求从URL获取主键(id)。我不知道您是如何开发后端的,但让我举一个.Net的例子
[HttpPut("{id}")]
public IActionResult Put(int id, [FromBody] BookViewModel book){}
如果您的put函数类似,则必须发送Id作为参数。为此,您需要更改服务上的haveRead方法。 service.ts
haveRead(book: Book): Observable<any> {
return this.http.put(this.baseUrl + "/" + book.id, book);
}