I've seen tutorials showing umpteen different ways to implement observables in Angular. Many of them seem overly complicated for my purposes. Others are for previous versions and no longer work.
Let's say I have a service with a single property named numChickens
, and I want to allow components to subscribe to that property. Do.i.really((need)=> to.chain((a)=>{million.garbledyGook().statements.to('gether)}) to make that work?
Here's the code for the service in question:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ChickenService {
public chickens: number;
constructor() { }
}
...and here is the code for a component which will use the observable:
import { Component, OnInit } from '@angular/core';
import { ChickenService } from '../chicken.service';
@Component({
selector: 'app-chickendisplay',
templateUrl: './chickendisplay.component.html',
styleUrls: ['./chickendisplay.component.scss']
})
export class ChickenDisplayComponent implements OnInit {
constructor(public cs: ChickenService) {
}
ngOnInit() {
}
}
In Angular 6, what is the simplest, most straightforward, most readable way to expose the chickens
property in ChickenService such that a component class has access to the value of that property as an observable stream? Or so that a component template can display the value using an async pipe?
I can't stress that enough - please, no answers that include an 8,192-character wall of closures and then say "see, it's simple".
I ask this question not just for myself, but for others like me who are trying to wrap their heads around observables and struggling with all of the dense and outdated tutorials on the subject. If you can reduce this solution to a simple form, future generations will thank you.