BehaviorSubject– object that holds value changing over time. Once we’ve had created BehaviorSubject that stores ID of active photo, we can display it easily. Let's add following code in
activePhoto$it will give us this value and, later, every next that comes to it. Our first value is empty string, since there’s no active photo when application starts.
onPhotoClickmethod with one argument:
photo.id. We want to change value of
activePhotoID$every time user clicks on photo. How do we implement
onPhotoClickto make sure it sends value to
activePhotoID$? We can do so in
active-photo. It will access a photo that is currently active and display it.
activePhotoID$and create new Observable out of it (of course in
propEqfrom ramda library:
activePhoto$and walk through the steps together.
pipemethod to transform it into something new. That’s what
pipedoes. Think of it like a coffee grinder - you put coffee in and get coffee out, but shaped just a little bit differently. It takes value from Observable and pipes it through RxJS operators that create new Observables. Our first
pipetakes photo ID and maps it to Photo object.
propEqsays exactly that: check if property named
mapoperator and return new Observable that finds photo based on ID.
activePhoto$Observable to display photo that user wanted to see!
BehaviorSubjectthat keeps value changing over time. You’ve used it to create new Observable! Now you get to display data from it. It surely requires a lot of work, or does it…? Let’s look at the code.
active-photo.component.tswe have to inject PhotoService in component's constructor and add:
app.component.html, just below the
activePhoto$from Photos service to Component field, so we can access
activePhoto$value in HTML. Because we access asynchronous value that changes over time, we need to use the
asyncpipe tells Angular it should subscribe to the asynchronous value and use new value every time it changes. Last part
?.urlmeans: check if
activePhoto$holds a value, if it does access
urlfield from it and display in HTML. Whew! We did it!
BehaviorSubject. This way Photos service will know to send our Components
activePhoto$Observable and no photo will be displayed.
active-photo.component.htmlfile, like this:
active-photo.component.tsand implement our handler.
noPhotoIDinstead of real ID. This way no active photo is displayed! What more can we do with our gallery? Maybe… let’s try adding some photos!