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看到我的更新.. –