Directly retrieve the result from http service (observable) without the need to return Observable from the function

Is there a way to directly return a result from the service without returning Observable and then using then clause? I've experimented with methods like pipe, of, take, toPromise, map, async-await, but none of them seem to return the result on a service call. Some of these methods aren't even available in the current version of RxJS. Can you provide any assistance?

Note: There is a condition where if the API fails, I need to retrieve data locally.


@Injectable()
export class SomeService {
  GetDataEitherFromApiOrFromLocalStorage(): any 
  {
    let result;
    this.http.get("https://"+ this.url +"/api/main/apidata").subscribe(
       next => {result = next;},
       error => {result = this.localData();},  
       () => {return result;}
    )
  }
}

When calling the function (which currently returns null, even with async-await)


@Component()
export class SomeComponent implements OnInit {

  constructor(private service: SomeService) {}

  ngOnInit() {
   let data = this.service.GetDataEitherFromApiOrFromLocalStorage();
  }
}

UPDATE:

I'm attempting this because I'd like to keep all the logic within the Service, rather than in the Component.

Answer №1

If you're looking for a solution, consider the following approach:

Both the promise route (at the end) and the observable route have been included.

Keep your api/data operations isolated in the service - components shouldn't be concerned with the implementation details.

GetDataEitherFromApiOrFromLocalStorage(): Observable<any> {
    return this.http.get('https://' + this.url + '/api/main/apidata').pipe(
        catchError((error) => {
            // Check if error is critical or expected
            let errorIsNotFatal = true;
            if (errorIsNotFatal) {
                return this.localdata(); // this function should return an observable;
            }
            return throwError(error);
        })
    );
}

Note: The catchError() block will handle both fatal errors and expected ones by fetching local data if needed.

        catchError((error) => {
           // Evaluate if error is fatal or expected
            errorIsNotFatal = true;
            if (errorIsNotFatal) {
                return this.localdata(); // this should return an observable;
            }
            return throwError(error);
        })

In order for localData() to work, it must also return an observable:

localdata(): Observable<any> {
    return of('anything or any kind of data');
}

Simply subscribe in your component and wait for the response:

export class SomeComponent implements OnInit {
    public data: any;

    constructor(private service: SomeService) {
    }

    ngOnInit() {
        this.service.GetDataEitherFromApiOrFromLocalStorage().subscribe((response) => {
            this.data = response;
        });
    }
}

Lastly - If you truly need a promise, you can create one like this. However, using observables is recommended over promises:

GetDataEitherFromApiOrFromLocalStorage(): Promise<any> {
    return new Promise((resolve, reject) => {
        this.http.get("https://" + this.url + "/api/main/apidata").subscribe(
            (next) => { resolve(next); },
            (error) => { reject(error); }
        );
    });
}

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

Transferring the date from an HTML input to a TypeScript file in Angular when the button

On my HTML page, I have two input fields for dates that need to be passed to the backend along with other parameters when a button is clicked. Here is the current setup: <input [owlDateTime]="dt1" placeholder="From a date" [value]="dateFrom.value"& ...

The type 'string[]' is missing the required property 'label', resulting in a typescript error

Within my codebase, I've defined a type called Person that looks like this : type Person = { value?: string[]; label?: string[]; }; Additionally, there is a promise function in my project: async function main(): Promise<Person> { const fo ...

The argument representing 'typeof Store' cannot be assigned to the parameter representing 'Store<AppState>'

I'm encountering an issue while trying to expand a service in Angular that utilizes ngrx. The error message I'm receiving is as follows: Argument of type 'typeof Store' is not assignable to parameter of type 'Store<AppState>& ...

Error: An unexpected character (.) was encountered | Building with npm has failed

When executing "npm run build", I encounter an error with the unexpected token (.) related to object values. Can someone assist me in resolving this issue? I am using tsc build for a react npm library. It seems like there might be a configuration problem ...

What could be causing the DOM not to update after updating the data set in Angular 2?

Currently, I am facing an issue in Angular 2 where I call a function of a child component from the parent. The child function updates my data set which initially loads the HTML. However, when I call the function again while on the same HTML, it displays in ...

Generating swagger documentation for TypeScript-based Express applications

I have successfully set up the swagger URL following a helpful guide on configuring Swagger using Express API with autogenerated OpenAPI documentation through Swagger. Currently, I am utilizing TypeScript which outputs .js files in the dist folder without ...

Exploring ways to retrieve a function-scoped variable from within an Angular subscribe function

Here's the scenario: I have a simple question regarding an Angular component. Inside this component, there is a function structured like this: somethingCollection: TypeSomething[] ... public deleteSomething(something: TypeSomething): void { // so ...

There was an issue locating the moment/ts3.1-typings/moment module

Encountering an ERROR after updating Angular version: Could not resolve moment/ts3.1-typings/moment in node_modules/ngx-daterangepicker-material/ngx-daterangepicker-material.d.ts ...

RouterLink causing component not to reload

In my welcome.component, I have a menu and tab. When I click on a menu item, the routerlink doesn't initiate a new request, causing the tab component not to reload. The tab component is called by multiple router links and should be reloaded every time ...

What seems to be the issue with my @typescript-eslint/member-ordering settings?

I am encountering an issue where my lint commands are failing right away with the error message shown below: Configuration for rule "@typescript-eslint/member-ordering" is throwing an error: The value ["signature","public-static-field","pro ...

Step-by-Step Tutorial: Displaying Loading Text in Child Components with Angular 4

Within my "event.component" file, I have a nested component (app-grouplist) <div class="group-list"> <app-grouplist [hasStarted]="started" [hasEnded]="ended" Displaying Loading Groups... </app-grouplist> </div> Upon the initial page ...

Troubleshooting Guide: Resolving the Error Message 'ControlContainerAngular' Provider Not Found in Your Angular App

Incorporating bootstrap-4 into my angular7 application for design purposes. <nav class="navbar navbar-light bg-light"> <form class="form-inline"> <div class="input-group"> <div class="inp ...

Issues arise when trying to update the modelValue in unit tests for Vue3 Composition API

Recently delving into Vue, I am currently engaged in writing unit tests for a search component incorporated in my project. Basically, when the user inputs text in the search field, a small X icon emerges on the right side of the input box. Clicking this X ...

What is preventing the spread type from being applied to `Record` in TypeScript?

export type AddResourceProps<K extends string, T extends any> = (resource: BasicResource) => Record<K, T> const addtionalResourse = addResourceProps ? addResourceProps(resource) : {} as Record<K,T> const result = { ...addtionalRe ...

Creating an Angular 2 project with DevExtreme in Visual Studio 2017/2015: A step-by-step guide

I would appreciate some guidance on setting up an Angular 2 project with DevExtreme control using Visual Studio 2017/2015. Specifically, I am interested in utilizing the control demonstrated at . Your assistance would be greatly appreciated. ...

Changing the size of a div component using Angular 6

Currently, I am working on implementing Angular's element resize feature. I am utilizing this library: https://github.com/mattlewis92/angular-resizable-element Here is my custom module: import { ResizableModule } from 'angular-resizable-elemen ...

Employing Typescript types in array notation for objects

Can someone please help me decipher this code snippet I found in a file? I'm completely lost as to what it is trying to accomplish. const user = rowData as NonNullable<ApiResult["getUsers"]["data"][number]["users"]> ...

Next.js v13 and Firebase are encountering a CORS policy error which is blocking access to the site.webmanifest file

Background: I am currently developing a website using Next.js version 13 in combination with Firebase, and I have successfully deployed it on Vercel. Upon inspecting the console, I came across two CORS policy errors specifically related to my site.webmani ...

Please enter data into the input fields provided in the text

Below is the code where Google transliteration is used for typing in Indian language in a text field. There are two routes with different page IDs. Initially, the transliteration works fine on the default page. However, when changing routes, an error occur ...

There are a pair of Ionic2 menus; one is currently visible while the other remains hidden

I am having an issue with my Ionic2 app where I have two pages, each with similar menus named XXX.html. One page displays its menu correctly, but the other does not show its menu at all. Is there a limitation in Ionic2 that prevents having two menus on the ...