Steps for linking HTTP requests in Angular 2 depending on the type of response

My attempt to create an api call from a remote server and then, if an error occurs, make another request from my local server is not working as expected. I am encountering errors and need help to determine if my approach is feasible.

Here is the code snippet from my service:

constructor(private _http: Http) { }
getAll(): Observable<any> {
    let result: any;
    this._http.get(url)
        .map((response: Response) => result = <any>response.json())
        .catch(this.getAllFromBackup);

    return result;
}

getAllFromBackup(): Observable<any> {
    return this._http.get(url)
        .map((response: Response) => <any>response.json())
        .catch(this.handleError);
}
private handleError(error: Response) {
    console.error(error);
    return Observable.throw(error);
} 

In my component, I have subscribed to the response:

export class JobComponent implements OnInit {
    allJobs: any;
    statusMasage: string = 'Loading you data...';

    constructor(private _jobService: JobService) { }

    ngOnInit() {
    this._jobService.getAll()
            .subscribe((jobData) => { console.log(jobData), this.allJobs = jobData },
            (error) => { this.statusMasage = 'There is propblem with the service please try again later.'});
    }

}

Answer №1

Yes, your proposed solution seems to be effective, however, there might be a simpler approach available.

If my understanding is correct, you are attempting to reattempt an HTTP request if it fails, correct?

Luckily, Observables provide a handy retry() method for this purpose.

You can implement it like so:

getAll(): Observable<any> {
    let result: any;
    this._http.get(url)
        .map((response: Response) => result = <any>response.json())
        .retry(1) // This will re-execute the request once in case of an error
        .catch(() => { console.log('Handle the 2nd error gracefully')});

    return result;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Trouble with 'import type' declaration causing build issues in a Next.js project

Having trouble importing the Metadata type from the next module. The code snippet below is directly from the Next.js documentation. THE ISSUE client.js:1 ./app/layout.tsx:3:12 Syntax error: Unexpected token, expected "from" 1 | import React from 'r ...

Issue 1068: Attribute not found within angular 2 (Ahead of Time Compilation)

I am currently learning Angular 2 and trying to create a "User Register" form. However, I encountered an error stating "Property does not exist on type" during Phone number validation. I am using both JIT and AOT compilers. With the JIT compiler, my user ...

Managing JSON object with irregular data in Angular 7: Best Practices

When the service returns data in a specific format, I am able to view the data in the developer tools. {"results":{"BindGridDatatable":[{"ID":"0005","Name":"Rohit"}, {"ID":"0006","Name":"Rahul"}], "Totalvalue":119}} ...

A method for comparing two arrays containing identical objects and then storing the results in a variable

I have an item stored within two other items called formKeyValues and form formKeyValues https://i.stack.imgur.com/nRfiu.png form https://i.stack.imgur.com/eDpid.png I am looking to extract only the keys and values from formKeyValues and place them in ...

Creating a custom Higher Order Component to seamlessly connect react-relay and react-router using TypeScript

Hey there! So, my Frankenstein monster project has decided to go rogue and I'm running out of hair to pull out. Any help would be greatly appreciated. I've been working on setting up a simple app with React, React-Router, React-Relay, and Typesc ...

Using angular2's ngRepeat to iterate over XML data

I have successfully transformed my XML data into JSON format to be utilized in Angular 2 within my view. However, as I attempt to loop through the data using a for(var... loop, I encounter an error message stating that it cannot find name array and that th ...

The perplexing behavior of RxJS Observables with Mongo Cursors

Recently, I've been working on converting a mongo cursor into an observable using my own RxJS implementation. Despite finding numerous solutions online, I wanted to challenge myself by creating one from scratch. I would greatly appreciate it if someo ...

Display the initial MUI components from an array of data in a distinctive manner

Trying to display the content of an Accordion by passing props down through a list array to a component. I have identified the issue but unsure how to call the component and pass the props differently. Below is the code snippet. Code for the parent compon ...

Attention: issue TS18002 has been detected - The 'files' configuration file is currently blank

I'm currently working with TypeScript version 2.1.5.0. My setup includes the grunt-typescript-using-tsconfig plugin, but I'm encountering an error when running the task. The issue seems to be related to the property "files":[] in my tsconfig.jso ...

Strategies for Implementing Pagination in an Angular 2 HTML Table Without the Use of Third-Party Tools

I have an HTML table that displays basic details along with images. I am looking to implement pagination for this table in Angular 2. Are there any alternatives to using ng2-pagination? ...

Enabling CORS header 'Access-Control-Allow-Origin' in Angular 2 using Typescript

I am currently developing an Angular 2 typescript application on my localhost. I recently encountered an issue when trying to access an external REST API in my application, resulting in the following error message: Cross-Origin Request Blocked: The Same ...

Guide on transforming a JSON string into an array of custom objects using the json2typescript NPM module within a TypeScript environment

I am looking to utilize the json2typescript NPM module to convert a JSON string into an array of custom objects. Below is the code I have written. export class CustomObject { constructor(private property1: string, private property2: string, private p ...

Transmit information from an Angular application to a Spring Boot server using a POST request

Attempting to send JSON data from a frontend Angular project to a Spring Boot backend for the first time. Limited experience with both technologies and unsure if the HTTP POST method in Angular is incorrect, or if the backend isn't receiving the expec ...

Retrieve the instance from the provider using its unique key without needing to inject its dependencies

I created a custom class called PermissionManager, which takes a list of Voter interfaces as an input in its constructor. export interface Voter { vote(): bool; } export class PermissionManager { constructor(private readonly ...

Can you modify a specific column in a table using mat-table in Angular material?

For my project, I am utilizing Angular Material's table to present data in a tabular format. However, due to a new requirement, I now need to enable in-line editing for the last 2 columns alongside highlighting another column when the user clicks on t ...

Ensuring Koa ctx.query is valid prior to invoking the handler function

I'm currently working on a basic route that looks like this: router.get('/twitter/tweets', async (ctx) => { const { limit, page, search } = ctx.query ctx.body = { tweets: await twitter.all(limit, page, search), } }) The issue I ...

Ways to utilize the scan operator for tallying emitted values from a null observable

I'm looking for an observable that will emit a count of how many times void values are emitted. const subject = new Subject<void>(); subject.pipe( scan((acc, curr) => acc + 1, 0) ).subscribe(count => console.log(count)); subject ...

Tips for expanding third-party classes in a versatile manner using Typescript

tl;dr: Seeking a better way to extend 3rd-party lib's class in JavaScript. Imagine having a library that defines a basic entity called Animal: class Animal { type: string; } Now, you want to create specific instances like a dog and a cat: const ...

Unresolved promise: Internal server issue

I encountered an exception while working on my Nativescript app. EXCEPTION: Uncaught (in promise): Server error JS: ORIGINAL STACKTRACE: JS: Error: Uncaught (in promise): Server error JS: at resolvePromise (/data/data/com.yourdomain.appname/files/app/ ...