Alex Palacios
Alex Palacios

Reputation: 389

Angular 2 Observable subscribe not working

I am trying to subscribe to an observable on init of a component like so:

    this.ticketService.getTicketsAsync(filters).subscribe(
        tickets => this.ticketResponse = tickets,
        () => console.log('hi'))

Is there any reason why the first lambda expression works, but the second one never does?

EDIT:

Here is the code hat getTicketAsync is returning:

getTicketsAsync(ticketFilters : TicketSearch): Observable<TicketResponse> {

    let api_endpoint = AppSettings.API_ENDPOINT + 'WebReport/request_report'
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({headers : headers, withCredentials : true});
    return this.http.post(api_endpoint, ticketFilters, options).map(this.extractData).catch(this.handleError);





}

Upvotes: 1

Views: 1549

Answers (2)

Kacper Polak
Kacper Polak

Reputation: 1411

The second one is catch when observable throw error.

subscription = source.subscribe(
  x => console.log('onNext: %s', x),
  e => console.log('onError: %s', e),
  () => console.log('onCompleted'));

https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/subscribe.md

Solution: 1. Use onNext hook:

this.ticketService.getTicketsAsync(filters).subscribe(
    tickets => {
      this.ticketResponse = tickets;
      console.log('hi');
    },
    () => console.log('ERROR!'));

2. Use onCompleted hook:

this.ticketService.getTicketsAsync(filters).subscribe(
  tickets => this.ticketResponse = tickets,
  error => console.log('ERROR: ' +error),
  () => console.log('hi')
);

Upvotes: 2

Jassi
Jassi

Reputation: 669

big arrows represent functions which makes your code like this

this.ticketService.getTicketsAsync(filters)
.subscribe(
  function(tickets){
    this.ticketResponse = tickets,
    function(){
      console.log("hi")
    }
  }
)

you are passing two arguments (which are two callback functions).

Upvotes: 0

Related Questions