Rus Mine
Rus Mine

Reputation: 1593

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

Upvotes: 2

Views: 9421

Answers (2)

Thierry Templier
Thierry Templier

Reputation: 202306

@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 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:

Upvotes: 7

Michael Kang
Michael Kang

Reputation: 52867

If you want to create an Observable (cold), you can use the create method:

myEvent:Rx.Observable<{item:Item}>;
myObserver: Rx.Observer<{item:Item}>;
constructor() {
    this.myEvent = Rx.Observable.create(o=>this.myObserver = o);
}
someEvent() {
    // do something
    var $event = {item:new Item()};

    // emit the event object when something interesting happens
    if(this.myObserver)
        this.myObserver.emit($event);
}

Upvotes: 3

Related Questions