Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare an observable on angular2


How can i declare an observable and how to add data to it in angular2 ? I have 5 hours trying to figure out how to do it.
I tryed this

this.products : Observable<array>;
var object = {"item":item};
this.products.subscribe(object)

everything i tryed throws me an error


I want to use it because i have an array of objects that is changing frequently and in the template the ngFor is not changing the values. Any help?

http://pastebin.com/1cFXJHHk Here is what i try to do

like image 943
Rus Mine Avatar asked May 06 '26 03:05

Rus Mine


1 Answers

@pixelbits provided a great answer describing the way to use raw observables.

But I think you misunderstood what observables and reactive programming are. You could have a look at this great introduction to start:

  • The introduction to Reactive Programming you've been missing - https://gist.github.com/staltz/868e7e9bc2a7b8c1f754

The subscribe method of obersables allows to register callbacks for notifications:

  • The first parameter for the callback regarding events
  • The second one for the callback regarding errors
  • The last one for the completion

Of course you can leverage events to add an element in a list but I'm not sure that it's your use case:

var someList = [];
let observable = (...)
observable.subscribe(data => {
  someList.push(data);
});

This is particularly useful for event-based tools / technologies like WebSockets, Firebase, ... The observable above would be linked on them. This answer could give you more details on how to implement this with Firebase:

  • I need a listener to see if my notifications table (node) has changed for real time data checking
like image 161
Thierry Templier Avatar answered May 09 '26 01:05

Thierry Templier