简体   繁体   English

Angular 6在POST后不更新视图

[英]Angular 6 not updating the view after POST

I just want to submit one input but angular doesn't update the list on the html component. 我只想提交一个输入,但是angular不会更新html组件上的列表。 I am using Web Api for backend. 我正在使用Web Api作为后端。

Service: 服务:

getRanks(): Observable<Rank[]> {
   return this.http.get<Rank[]>(this.rankUrl);
}

Component.ts: Component.ts:

ngOnInit() {
   this.getRanks();
}

newRank: any = {};

saveRank(rank: Rank) {
   this.rankService.addRank(rank).subscribe();
}

getRanks(): void {
   this.rankService.getRanks()
      .subscribe(
         ranks => {
           this.ranks = ranks;
   });
}

Component.html: Component.html:

<div class="col-md-6 text-center">
<input  [(ngModel)]="newRank.Name">
   <button (click)="saveRank(newRank)">Save</button>
</div>
<div *ngFor="let rank of ranks"> {{rank.Name}}

</div>

I stripped the code as much as I could from the original one but it still behaves the same. 我从原始代码中剥离了尽可能多的代码,但其行为仍然相同。 I also commented everything that is not related to post and get methods. 我还评论了与post和get方法无关的所有内容。

I checked other answers and tried to use zone and changeDetection: ChangeDetectionStrategy.Default 我检查了其他答案,并尝试使用zone和changeDetection: ChangeDetectionStrategy.Default

If I refresh the page then it shows up, so its submitted in the database but it doesn't show up after submission. 如果刷新页面,则会显示该页面,因此该页面已在数据库中提交,但提交后未显示。

Any ideas? 有任何想法吗? Any other info I should provide? 我应该提供其他信息吗?

Thank you 谢谢

You should call the getRanks() function in the subscribe success function like this: 您应该像这样在subscribe success函数中调用getRanks()函数:

saveRank(rank: Rank) {
   this.rankService.addRank(rank)
    .subscribe(_ => this.getRanks());
}

you need to refresh your ranks object. 您需要刷新等级对象。 simply you can call this.getranks(); 只需调用this.getranks();

saveRank(rank: Rank) {
   this.rankService.addRank(rank).subscribe(_ => this.getRanks());
}

or 要么

this.rankService.addRank(rank).subscribe( _=> ranks.push(rank));

if you don't want to all this.getRanks, add manually the item to the array "rank" 如果您不想要所有this.getRanks,请将该项目手动添加到数组“ rank”

saveRank(rank: Rank) {
   this.rankService.addRank(rank)
    .subscribe(_ => this.ranks.push(rank)); //<--push the array
}

or change your API so, the API call to saveRank, return all the ranks 或更改您的API,以便API调用saveRank,返回所有排名

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM