I am struggling to understand , why i need to use observable. I have a very simple store like below
@Injectable({
providedIn: 'root'
})
export class DataService {
private readonly personData: Person = new Person();
constructor() {
}
public getPerson():Person{
return this.personData;
}
public setAge(age:number){
this.personData.age = age;
}
}
this above service works just fine and exactly same if I were to use observable
@Injectable({
providedIn: 'root'
})
export class DataService {
// @ts-ignore
private readonly personData: BehaviorSubject<Person> = new BehaviorSubject<Person>({});
public personData$: Observable<Person> ;
constructor() {
this.personData$ = this.personData.asObservable();
}
public getPerson():Person{
return this.personData.getValue();
}
public setAge(age:number){
this.getPerson().age = number;
}
}
My question is , why would I use observable , the simple service property is working just fine! Or I am missing the big picture! Please help me to understand.
Observables are useful when you want to share the same data with multiple components since they can all subscribe to the same source and keep getting the latest updated data. For basic use cases, this is may not seem useful, but in large projects it certainly is.
They're also very useful when optimizing angular's change detection using the OnPush detection strategy. An observable can tell the view that it has been updated, so the view should be updated as well. Async pipe
So if you're not using the OnPush detection strategy, or your project is pretty basic in its functionality, you may not really need observables, but since they're extremely useful, and to be honest, kinda hard to work with, I'd say use them anyway if for nothing but learning. They give you a new way of thinking about things.
Lookup "Reactive Programming".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With