0

我正在尝试开发一个Angular应用程序,其中存在我正在调用订阅了HTTP服务的服务的情况。我已经编写了一个警报提示服务,当按下“ok”时内部调用HTTP服务。像这样:Angular 2订阅订阅另一个异步函数的服务

this.alertservice.prompt(url); 

这会提示用户进行确认。如果用户点击“确定”后,警报服务将在内部调用HTTP服务:

this.httpservice.get(url).subscribe(res => { 
    console.log(res); 
}); 

现在我想告诉家长呼叫者的呼叫失败还是成功。例如:

this.alertservice.prompt(url).subscribe(res => { 
    console.log("success or failure"); 
}); 

但我不理解如何订阅警报功能。我该怎么做呢?

回答

0

也许是这样的:

import {..., EventEmitter} from '@angular/core'; 

export class AlertService { 

    ... 

    prompt(url:string): Observable<boolean> { 

     let result = new EventEmitter<boolean(); 

     this.httpService.get(url).subscribe 
      (
      (res) => { 
       console.log("OK:", res); 
       result.emit(true); 
       result.complete(); 
      }, 
      (error) => { 
       console.log("ERROR:", error); 
       result.emit(false); 
       result.complete(); 
      } 
     ); 
     return result; 
    } 
} 

现在你可以订阅提示() - 功能:

this.alertService.promp(url).subscribe((okOrNotOk) => { 
    // okOrNotOk will be true, when the url was retrieved successfully, 
    // otherwise false 
}); 

我不是rxjs的专家,也许是有更好的方法来做到这一点。

+0

很酷的工作如期:)谢谢 –

+0

如果您发现更好的答案,请更新答案,以便任何人搜索此获得收益 –

+0

它不是rxjs方式。您应该使用内置错误通知方法(例如subscribe中的第二个回调)而不是bool回调参数。 –

1

在子服务中使用do,在父服务中使用catch进行错误处理。

child() { 
    return this.httpservice.get(url).do(res=> 
    {console.log(res)} 
).catch(e => { 
    console.log("handle error"); 
    }); 
} 

parent() { 
    this.child(url).subscribe(res=>{ 
    console.log("success"); 
    }, e => { 
    console.log("or failure"); 
    }); 
} 
+0

实际上不能处理父组件中的错误,因为它的sweetalert回调和大部分代码已经基于此服务已经写好了。我必须在alert组件中执行错误处理并向parent.Is发送一个字符串或布尔值有可能吗? –

+0

@vikk看到我的更新.. –