我正在通过ng-bootstrap模式添加我的数据,但是由于当我点击添加按钮时,它需要刷新才能看到新添加的数据。我已经叫this.getMaterials()当我成功添加的产品,但它仍然需要被刷新之前,我可以看到新增加的数据需要重新加载浏览器才能看到角度的变化
export class MaterialsListComponent implements OnInit {
closeResult: string;
materials: any;
subscription: Subscription;
constructor(private modalService: NgbModal, private materialsService: MaterialsService) { }
ngOnInit() {
this.getAllMaterials();
}
getAllMaterials() {
this.subscription = this.materialsService.getAll()
.subscribe(
(data:any) => {
this.materials = data;
console.log(data);
},
error => {
console.log(error);
});
}
onCreateMaterial(form: NgForm){
const name = form.value.name;
const description = form.value.description;
this.materialsService.addMaterial(name, description)
.subscribe(
data => {
this.getAllMaterials();
console.log(data);
},
error => {
console.log(error);
});
}
open(content) {
this.modalService.open(content).result.then((result) => {
this.closeResult = `Closed with: ${result}`;
}, (reason) => {
this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
});
}
private getDismissReason(reason: any): string {
if (reason === ModalDismissReasons.ESC) {
return 'by pressing ESC';
} else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
return 'by clicking on a backdrop';
} else {
return `with: ${reason}`;
}
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
服务
export class MaterialsService {
url = AppSettings;
materials: any;
constructor(private httpClient: HttpClient) {}
getAll() {
if(!this.materials) {
this.materials = this.httpClient.get<any>(this.url)
.map((response => response))
.publishReplay(1)
.refCount();
}
return this.materials;
}
addMaterial(name: string, description: string) {
return this.httpClient
.post(
this.url,
JSON.stringify({ name, description})
)
.map((response: any) => {
return response;
});
}
您应该使用RxJs主题实时更新数据。 http://reactivex.io/documentation/subject.html –
@HaHoang。如果你能用我的代码来帮助我,那将是非常棒的。谢谢 –