我对服务进行了GET XMLHttpRequest,并将其作为以下JSON有效负载的响应:
{_id: "5aa1358d32eba9e34dd9f280", source: "Avengers", target: "Iron Man", enemies: "Actor"}
我在src / app中有对象英雄:
export class Hero {
_id: number;
target: string;
source: string;
enemies: string;
}
TS组件中用于获取数据的代码:
ngOnInit(): void {
this.route.params.subscribe((params: Params) => {
const id = params['id'];
this.getHero(id);
});
}
getHero(id: string): void {
this.heroService.getHero(id)
.subscribe(hero => this.hero = hero);
}
服务中方法的代码:
getHero(id: string): Observable<Hero> {
// Todo: send the message _after_ fetching the hero
this.messageService.add(`HeroService: fetched hero id=${id}`);
const url = `${this.herodetailUrl}/${id}`;
return this.http.get<Hero>(url);
}
以下是我在视图中的代码:
<label>name:
<input [(ngModel)]="hero.target" (input)="hero.target =
$event.target.value" placeholder="target" /> </label>
<label>group:
<input [(ngModel)]="hero.source" (input)="hero.source =
$event.target.value" placeholder="source" /> </label>
<label>enemies:
<input [(ngModel)]="hero.enemies" (input)="hero.enemies =
$event.target.value" placeholder="enemies" /> </label>
绑定不起作用
在我的表单元素中,我看到了占位符的名称。不是值
此致
劳伦
答案 0 :(得分:0)
<label>name:
<input [(ngModel)]="hero.target" (input)="hero.target =
$event.target.value" placeholder="target" /> </label>
<label>group:
<input [(ngModel)]="hero.source" (input)="hero.source =
$event.target.value" placeholder="source" /> </label>
<label>enemies:
<input [(ngModel)]="hero.enemies" (input)="hero.enemies =
$event.target.value" placeholder="enemies" /> </label>
当您使用 [(ngModel)] 时,您不需要(输入)=“hero.target = $ event.target.value”
答案 1 :(得分:0)
JSON是一个对象的数组,所以我修改了我的视图:{{hero [0] .target |每个表单组件的大写}}等等。现在它按原样运行:
> <div><span>id: </span>{{hero[0]._id}}</div> <div>
> <label>name:
> <input [(ngModel)]="hero[0].target" placeholder="target"/>
> </label>
> <label>group:
> <input [(ngModel)]="hero[0].source" placeholder="source"/>
> </label>
> <label>enemies:
> <input [(ngModel)]="hero[0].enemies" placeholder="enemies"/>
> </label>
现在绑定工作