添加新项目后,我的观点有问题。看到新项目后,我需要重新加载网页。我怎样才能让它检测到变化,我想要发生的是,在我添加一个新项目后,视图也在更新。下面是我的代码
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;
});
}