首页 文章

Angular 2 Observable订阅不起作用

提问于
浏览
1

我试图订阅一个像init这样的组件的observable:

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

有没有理由说第一个lambda表达式可以工作,但第二个表达式从不这样做?

编辑:

以下是getTicketAsync返回的代码帽:

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





}

2 回答

  • 0

    当观察到抛出错误时,第二个是 catch .

    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.使用 onNext hook:

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

    2.使用 onCompleted 钩子:

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

    大箭头代表使你的代码像这样的函数

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

    你传递两个参数(这是两个回调函数) .

相关问题