1

I'm buiding an application that is suppose to trigger an http.get request and retrigger the request every 5 seconds if an error occures. But I need to be able to display this error on Screen while the request is retriggered.

I didn't find any solution with rxjs's retry/retryWhen because they simply intercept the error before retriggering, and I can't get to subscribe to the error.

Here's my code:

Service:

@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:

@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;
            }
        );
    }
}
cartant
  • 57,105
  • 17
  • 163
  • 197
WizMik
  • 17
  • 1
  • 4

2 Answers2

2

I'd suggest moving the retry logic out of the 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)
   );
}
paulpdaniels
  • 18,395
  • 2
  • 51
  • 55
-2

implement an Observable.Interval to make your http request every 5s. have a look at this thread : Angular2 http at an interval

sancelot
  • 1,905
  • 12
  • 31