0

In Rxjs ,I know the subscribe method has three three types of values an Observable Execution:next,error,complete.It's easy to write a arrow function in subscribe() method,but I met the subscribe({}) method somewhere .So I don't know what it means.for example:

var observable = Rx.Observable.create(function (observer) { observer.next(1); observer.next(2); observer.next(3); setTimeout(() => { observer.next(4); observer.complete(); }, 1000); }); console.log('just before subscribe'); observable.subscribe({ next: x => console.log('got value ' + x), error: err => console.error('something wrong occurred: ' + err), complete: () => console.log('done'), }); console.log('just after subscribe'); 

in this example it use the observable.subscribe({}),and different expression example like the follow:

getHeroes() { this.heroService.getHeroes() .subscribe( heroes => this.heroes = heroes, error => this.errorMessage = <any>error); } 
2
  • Provide the complete expression. Commented Nov 9, 2016 at 2:46
  • I have updated the question ,wonder if it is clearly ,thanks for your advice Commented Nov 9, 2016 at 3:48

2 Answers 2

2

There are two ways you can call .subscribe():

  • Passing in an observer as a single parameter
  • Passing in 1-3 callbacks for onNext, onError, onComplete

The approach you seem to be familiar with is the latter. At its core, an observer is just an object with a .next(), .error(), and .complete() method and internally, these are the methods that observables call on each event.

Your first code example is indeed passing in an object with these three methods, so this works successfully as an observer, but I can't see anything to indicate that you're supposed to be able to use a plain object like that as an observer. If you want to use an observer, you should create an actual observer and pass that in:

var observer = Rx.Observer.create( x => console.log('got value ' + x), err => console.error('something wrong occurred: ' + err), () => console.log('done') ); observable.subscribe(observer); 
Sign up to request clarification or add additional context in comments.

2 Comments

The link you provided is for RxJS v4 and below. From v5 onwards, which Angular 2 uses, the documentation on Observers is found at the new repo for v5.
@GregL yes,you point out the key.and is there any abundance tutorial about Rxjs v5?
0

That's not specific to subscribe(), that's the same for every method or function call. It's about passing parameters by position or by name. When an object literal is passed the passed values are assigned to method parameters using the object property names. {} is just an empty object (no parameters).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.