我正在使用Angular 7和json-server;目前,我可以成功使用get和delete方法,但是post方法仅发布id并忽略同一类的其他3个属性
主页HTML
<form (ngSubmit)="addUser()" class="col-md-6 offset-md-3">
<div class="row">
<div class="col-md-6 offset-md-3">
<input required class="form-control top-dist" placeholder="name" type="text" [(ngModel)]="hero.name" name="name" />
</div>
<div class="col-md-6 offset-md-3">
<input required type="number" class="form-control top-dist" placeholder="age" name="age" [(ngModel)]="hero.age"/>
</div>
<div class="col-md-6 offset-md-3">
<input required name="email" class="form-control top-dist" type="email" placeholder="email" [(ngModel)]="hero.email" />
</div>
<div class="col-md-6 offset-md-3 text-center">
<div >
<input type="submit" value="submit" class="btn btn-danger top-dist " />
</div>
</div>
</div>
</form>
首页TS:
export class HomeComponent implements OnInit {
heroes: Hero[];
hero: Hero = {
id: null,
name: null,
age: null,
email:null
};
constructor(private dataService: DataService) {
}
ngOnInit() {
this.getHeroes();
}
getHeroes() {
this.dataService.getHeroes().subscribe(data => {
this.heroes = data;
console.log(data)
})
}
addUser(){
if(this.hero.name!=null && this.hero.age!=null && this.hero.email!=null){
this.dataService.addUser(this.hero).subscribe((data: Hero)=>{console.log(data)})
}
};
}
服务:
addUser(user: Hero){
console.log(user) ---> logs all fields
if(user.id===null){
return this.http.post<Hero>(this.url, user, {
headers: new HttpHeaders ({
'Content-Type':'aplication/json'
})
})
}
}
在该服务中,我可以看到所有用户字段都已登录到控制台,但是回到home组件,记录了已订阅的observable,我只能看到ID,因此仅在显示ID之后。有人可以帮忙吗?
这是家庭的日志。前四个写在文件中,其他四个带有发布请求:
答案 0 :(得分:0)
My guess is that the API endpoint is setup to only return Id on POST requests, which is a common pattern. To get around overwriting your other object properties, one thing you can try:
this.dataService.addUser(this.hero).subscribe(
(data: id) => this.hero = Object.assign({}, this.hero, { id: id })
)