How to declare an observable on angular2

2019-09-10 01:05发布

问题:


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

回答1:

@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


回答2:

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);
}