Search code examples
angularhttprequestrxjsobservablepolling

Angular2 - How can I retry after an HTTP Request fails and still subscribe to the error?


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

Solution

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