2017-08-03 40 views
0

我構建了一個應用程序,假設發生錯誤時每5秒觸發一次http.get請求並重新觸發請求。但是我需要能夠在請求被重新觸發時在屏幕上顯示這個錯誤。Angular2 - 如何在HTTP請求失敗後重試並仍然訂閱錯誤?

我沒有找到任何與rxjs重試/重試的解決方案,因爲他們只是在重新觸發前攔截錯誤,我無法訂閱錯誤。

這裏是我的代碼:

服務:

@Injectable() 
export class CompanyService extends WabelService { 
    constructor (private http: Http) { 
     super(); 
     this.service_uri = "company"; 
    } 

    getCompany(id: string): Observable<Company> { 
     return this.http.get(this.url+"/"+id) 
      .retry() 
      .map(response => response.json()); 
    } 
} 

組件:

@Component({ 
    selector: 'app', 
    templateUrl: 'app.component.html', 
    styleUrls: ['app.component.less'], 
    providers: [CompanyService] 
}) 
export class EeeComponent implements OnInit { 
    target: any; 
    error: CustomError; 

    constructor(
     private route: ActivatedRoute, 
) {} 

    ngOnInit(): void { 
     this.route.params 
      .switchMap((params: Params) => this.companyService.getCompany(params['id'])) 
     .subscribe(
      (company) => this.target = company, 
      (error) => { 
       // Can't reach this ! 
       this.error = error; 
      } 
     ); 
    } 
} 

回答

-2

實施Observable.Interval盡一切5S您的HTTP請求。看看這個線程:Angular2 http at an interval

+0

好吧,我的壞,我看到了這個線程,但因爲某種原因放棄了它。它像一個魅力! – WizMik

1

我建議將重試邏輯移出companyService

ngOnInit(): void { 
    this.route.params 
    .switchMap(({id}) => 
    this.companyService.companyService.getCompany(id) 

     // Handle the retry logic here instead so you have access to this.error 
     .retryWhen(e => 

     // Set the error when you receive one 
     e.do({ 
      error: err => this.error = err 
     }) 

     // Delay each error by 5 seconds before emitting for a retry 
      .delayTime(5000) 

     // Optionally stop trying after a while 
     .take(10) 
     ) 

     // If you get out here then the error has been dealt with 
     // and you can disable your error state 
     .do(_ => this.error = null) 
    ) 
    .subscribe(
    company => this.target = company, 
    fatalError => console.error('Something really bad happened', fatalError) 
    ); 
} 
+0

謝謝!這非常有幫助。但在我的Angular版本中,我必須使用'delay(5000)'而不是delayTime –

相關問題