我决定开始学习 Angular(我使用的是 15.0.3 版本)并做一些 CRUD。 我的应用程序与我的 api 连接良好(我通过 Symfony 使用 api-platform),该方法 GetCollection() 有效。
另一方面,一旦我完成 Post() 方法的设置,我就会收到此消息:此操作不允许更新。 我进行了各种搜索,但没有解决我的问题。 你有想法吗?
提前致谢
这是我的实体
#[ORM\Entity(repositoryClass: SerieRepository::class)]
#[
ApiResource(
operations: [
new Meta\GetCollection(),
new Meta\Post(),
new Meta\Get(
uriTemplate: '/series/name/{name}',
uriVariables: 'name'
),
new Meta\Get(),
new Meta\Patch(),
new Meta\Delete()
],
normalizationContext: [
'groups' => ['series:read']
],
denormalizationContext: [
'groups' => ['series:post']
],
)
]
class Serie
{
#[
ORM\Id,
ORM\GeneratedValue,
ORM\Column,
Meta\ApiProperty(identifier: true),
Groups(['series:read','books:read'])
]
private ?int $id = null;
#[
ORM\Column(length: 100, unique: true),
Groups(['series:read','series:post','books:read'])
]
private ?string $name = null;
#[
ORM\OneToMany(mappedBy: 'serie', targetEntity: Book::class),
Groups(['series:read'])
]
private Collection $books;
public function __construct()
{
$this->books = new ArrayCollection();
}
[...]
为实体服务
create(serie: Serie): Observable<Serie> {
return this.http.post<Serie>(
'http://127.0.0.1:8000/api/series',
serie,
{
headers: {'Content-Type':'application/json'},
responseType: "json",
}
)
}
还有组件
export class SeriesPostComponent {
serie: Serie;
constructor(private _formBuilder: FormBuilder, private serieService: SerieService, private snackBar: SnackBarComponent) {
this.serie = new Serie(0,"",[]);
}
nameFormGroup = this._formBuilder.group({ firstCtrl: ['', Validators.required], });
addSerie(): void {
this.serie.name = this.nameFormGroup.value.firstCtrl ?? '';
this.serieService.create(this.serie as Serie).subscribe(
data => { this.snackBar.successSnackBar(`la série < ${data.name} > à été ajouté`) },
echec => {
this.snackBar.errorSnackBar(echec.error.detail)
console.log(echec);
}
);
}
}
编辑: Put()、Get()、Delete() 方法有效。但还是没有Post()
编辑*: 我将我的服务创建方法更改为这样
create(serie: Serie): Observable<Serie> {
return this.http.post<Serie>(
this.seriesurl,
{
'name': serie.name
},
{
headers: {'Content-Type':'application/json'},
responseType: "json",
}
)
}
它奏效了。 有人能给我解释一下为什么吗?
很可能您在请求中传递“id”字段,并且 API 平台中的 ItemNormalizer 类会抛出该错误 - 这是一个已知问题,您可以在 github 上找到它(和解决方案) 或者干脆不传递“id”字段 - 排除它、重命名它等等。