[英]Angular 5 best practice for updating a single object with RxJS
I'm building an Angular 5 application that let's you track the score of an ongoing martial arts match. 我正在构建一个Angular 5应用程序,可让您跟踪正在进行的武术比赛的得分。 The score is input into the DB from a desktop application. 分数从桌面应用程序输入到数据库中。 The webapp then gets the score as a single scoreboard object from a Angular service that calls an API with the Id for the match and uses the retrieved object in the component to display the score for the two fighters. 然后,webapp从Angular服务获取得分作为单个记分牌对象,该服务调用具有ID的API进行比赛,并使用组件中检索到的对象显示两个战士的得分。 The user will refreshes the score by a button click (or maybe on a timer.) 用户将通过单击按钮(或在计时器上)刷新分数。
I'm very new to both Angular and RxJs, and the trouble I'm having is finding a examples of how to do this WELL. 我对Angular和RxJ都非常陌生,而我遇到的麻烦是找到一个如何做到这一点的例子。
Right now I've got it working by getting scoreboards for ALL matches and then using map and find to filter out the one I want. 现在,我通过获取所有比赛的记分牌,然后使用map来查找想要的一个,来使它起作用。 It feels very crude. 感觉很粗糙。
To summarize what I need to do. 总结一下我需要做什么。 Make a call to a service method with a unique Id. 用唯一的ID调用服务方法。 Get a single object from the API with the Id. 使用ID从API获取单个对象。 return that object to the component and assign it to a property. 将该对象返回给组件并将其分配给属性。
Any and all advice is greatly appreciated! 任何和所有建议,不胜感激!
In your service, you should have a method that returns single Score
. 在您的服务中,应该有一个返回单个Score
的方法。 Something like: 就像是:
getSingleScore(id:string):Observable<Score>{
return yourHttpCallToAPI...
}
Then in your component, you can have a property that gets that Observable
: 然后在您的组件中,您可以拥有一个获取Observable
的属性:
singleScore$:Observable<Score>;
ngOnInit(){
this.singleScore$ = myService.getSingleScore(id);
}
finally, in your template, bind singleScore$
with async
pipe: 最后,在您的模板中,将singleScore$
与async
管道绑定:
<div *nfIg="singleScore$ | async as score">Whatever property: {{score.whatever}}</div>
PS. PS。
...*nfIg="singleScore$ | async as score"
is a good practice since that way you resolve async
only once and not as many times as you have properties you want to show. ...*nfIg="singleScore$ | async as score"
是一种好习惯,因为这样一来,您解析一次async
次数就不会超过要显示的属性的次数。
ref: https://angular.io/api/common/NgIf#storing-conditional-result-in-a-variable 参考: https : //angular.io/api/common/NgIf#storing-conditional-result-in-a-variable
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.