我有一堂课
export class Thing {
id:number;
name: string;
link: string;
liked: boolean;
}
数据库(内存Web API):
createDb() {
const things = [{
id: 1,
name: "Ian",
link:"http://1",
liked:false
},
...
];
return {things};
}
模板:
<ul>
<li *ngFor="let thing of things">
<p>id:{{thing.id}}</p>
<p>name: {{thing.name}}</p>
<p>link: {{thing.link}}</p>
<label>
<p>{{thing.liked}}</p>
<input ([ngModel])="thing.liked" type="checkbox" data="toggle" (change)=onLike(thing)>
</label>
</li>
</ul>
things.component:
import { Component, Input, OnInit } from '@angular/core';
import { Thing } from '../thing';
import { ThingService } from '../thing.service';
@Component({
selector: 'app-thing',
templateUrl: './thing.component.html',
styleUrls: ['./thing.component.css']
})
export class ThingComponent implements OnInit {
things: Thing[];
@Input() thing: Thing;
constructor(private thingService: ThingService) { }
getThings(): void {
this.thingService.getThings()
.subscribe(things => this.things = things);
}
onLike(x): void{
x.liked = !x.liked;
this.thingService.saveThing(x).subscribe(things => this.things = things);
}
ngOnInit() {
this.getThings();
}
}
thingService方法:
saveThing(thing: Thing): Observable<any>{
return this.http.put(this.thingsUrl, thing, httpOptions)
}
当我单击一个复选框时,我希望“ liked”属性会更改其值(确实如此),并且对象“ thing”将使用此新值“ liked”(而不是在“ liked之后”)保存到数据库中”值更改了,整个列表都消失了)。问题出在哪里?
UPD:
我添加了getThings()方法,以更改复选框
onLike(x): void{
x.liked = !x.liked;
this.thingService.saveThing(x).subscribe(things => this.things = things);
this.getThings();
}
但是我希望刷新页面时此值保持新的状态。不是
答案 0 :(得分:0)
这是因为您正在使用in-memory-web-api,它不会持久存储数据,createDb将再次运行,而ngOnInit将再次运行。如果使用真正的Web api,则它将获取数据库中存储的数据,因为ngOnInit将在页面刷新时运行。如果要在刷新时保留数据,则需要将其存储在本地存储或真实数据库中