添加新项目后,我的视图中出现问题。我看到新项目后需要重新加载网页。如何让它检测到更改,我想要发生的是,在我添加新项目后,视图也在更新。这是我的代码
TS
export class ProjectsListComponent implements OnInit {
closeResult: string;
projects: any;
subscription: Subscription;
constructor(private modalService: NgbModal, private projectsService: ProjectsService) { }
ngOnInit() {
this.subscription = this.projectsService.getAll()
.subscribe(
(data:any) => {
this.projects = data.projects;
console.log(data);
},
error => {
alert("Error");
});
}
onCreateProject(form: NgForm){
const name = form.value.name;
const description = form.value.description;
this.projectsService.addProject(name, description)
.subscribe(
data => {
alert("Success Adding");
console.log(data);
},
error => {
alert("Error Adding");
console.log(error);
});
}
}
服务
@Injectable()
export class ProjectsService {
url = App.URL + '/projects';
projects: any;
constructor(private httpClient: HttpClient) {}
getAll() {
if(!this.projects) {
this.projects = this.httpClient.get<any>(this.url)
.map((response => response))
.publishReplay(1)
.refCount();
}
return this.projects;
}
addProject(name: string, description: string) {
return this.httpClient
.post(
this.url,
JSON.stringify({ name, description })
)
.map((response: any) => {
return response;
});
}
答案 0 :(得分:1)
像这样更改ts
代码:成功更新后需要重新获取列表。
export class ProjectsListComponent implements OnInit {
closeResult: string;
projects: any;
subscription: Subscription;
constructor(private modalService: NgbModal, private projectsService: ProjectsService) { }
ngOnInit() {
this.getAllProjects();
}
onCreateProject(form: NgForm){
const name = form.value.name;
const description = form.value.description;
this.projectsService.addProject(name, description)
.subscribe(
data => {
alert("Success Adding");
console.log(data);
getAllProjects(); // <== Fetching list again after project add
},
error => {
alert("Error Adding");
console.log(error);
});
}
getAllProjects(){
this.subscription = this.projectsService.getAll()
.subscribe(
(data:any) => {
this.projects = data.projects;
console.log(data);
},
error => {
alert("Error");
});
}
}