简体   繁体   中英

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. 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. 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.

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. It feels very crude.

To summarize what I need to do. Make a call to a service method with a unique Id. Get a single object from the API with the Id. 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 . Something like:

getSingleScore(id:string):Observable<Score>{
   return yourHttpCallToAPI...
}

Then in your component, you can have a property that gets that Observable :

singleScore$:Observable<Score>;

ngOnInit(){
   this.singleScore$ = myService.getSingleScore(id);
}

finally, in your template, bind singleScore$ with async pipe:

<div *nfIg="singleScore$ | async as score">Whatever property: {{score.whatever}}</div>

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.

ref: https://angular.io/api/common/NgIf#storing-conditional-result-in-a-variable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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