There are countless tutorials out there demonstrating various ways to implement observables in Angular, but many of them are too complex for my needs. Some are outdated and no longer applicable.
Let's assume I have a service with a single property called numChickens
, and I want components to be able to subscribe to that property. Do I really need to go through a million convoluted statements to make this work?
Below is the code for the service:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ChickenService {
public chickens: number;
constructor() { }
}
...and here is the code for a component that will utilize 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 and most readable way to expose the chickens
property in ChickenService so that a component class can access the value of that property as an observable stream? Or so that a component template can display the value using an async pipe?
I want to emphasize - please, no lengthy closures followed by claiming it's simple.
I am not just asking this question for myself, but also for others who are struggling to understand observables amidst the overwhelming and outdated tutorials. Simplifying this solution will benefit future developers. Thank you.