"Patience is key: waiting for an HTTP response in Angular 2

I am currently utilizing HTTP requests in Angular 2. My objective is to trigger the next process once I receive a response from the HTTP request.

For example: In a form, the select options are populated through an HTTP GET request. I aim for the form page to remain loading until I receive a response with the select options.

Function to retrieve select option value:

getSelectOptionValue(): any {
      let area_list_url = '/select_option_list/';

      this.urlGet(area_list_url).subscribe(
        (response) => {
          let data = response.text() ? response.json() : [{}];
          if (data) {
            Constant.areaList = data;
          }
        }
      );
    return JSON.stringify(Constant.areaList);
  }

Function for GET request:

 urlGet(url: string) {

    return this._http.get(Constant.hostUrl + url, {headers: GlobalUtils.head})
      .map((res)=> {
        if (res.status === 200) {
          console.log(res);
          return res;
        } else if (res.status = 201) {
          return res;
        }
      }).catch((error)=> {
        console.log(error);

        if (error.status === 400) {
          return Observable.throw(new Error(error.status));
        } else if (error.status === 401) {
          return Observable.throw(new Error(error.status));
        } else if (error.status === 403) {
          return Observable.throw(new Error(error.status));
        } else if (error.status === 404) {
          return Observable.throw(new Error(error.status));
        } else if (error.status === 420) {
          return Observable.throw(new Error(error.status));
        } else {
          return Observable.throw(new Error(error.status));
        }
      });
  }

Answer №1

Waiting for asynchronous calls to return in code is not possible.

However, you can create a chain of async calls so that when one call returns, certain portions of your code can be executed.

Using the map() function instead of subscribe() allows you to return the created Observable for the caller to subscribe to. If you use subscribe(), the return value will be a Subscription, which is typically not very beneficial for the caller:

getSelectOptionValue(): any {
      let area_list_url = '/select_option_list/';

      return this.urlGet(area_list_url).map( /// <<<=== use `map` here
        (response) => {
          let data = response.text() ? response.json() : [{}];

          if (data) {
            Constant.areaList = data;
          }

          return JSON.stringify(Constant.areaList);
        }
      );
    }
}

You can then utilize it as follows:

this.getSelectOptionValue().subscribe(data => {/* your code that works with received data here */ });

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

Monitor modifications to documents and their respective sub-collections in Firebase Cloud Functions

Is it possible to run a function when there is a change in either a document within the parent collection or a document within one of its subcollections? I have tried using the code provided in the Firebase documentation, but it only triggers when a docume ...

Is it possible to transform a tuple type into a union?

Is it possible to map a tuple's generic type to a union type? type TupleToUnion<T> = T[keyof T]; // This will include all values in the tuple const value: TupleToUnion<[7, "string"]> = 2; // This assignment should not be permitted since ...

Testing Angular 4 routing with router.url

Is there a way to simulate router.url in Angular 4 unit testing? In my component, I'm using router.url in the ngOnint function but in my test, the value for router.url is always '/'. ...

Notifying users with Angular bootstrapped alerts directly from a

I have a service that is set up to listen for incoming events. When an event occurs, I need to notify the user. Currently, I am using alert(). My goal is for a Bootstrap alert to pop up in every component when the service triggers. Is there a way to achie ...

Removing query parameters in Angular when clicking the back button

I am in need of a way to verify if my income URL follows a specific format and then open a modal to perform an action. I have achieved this using the following code: route.queryParams.subscribe(async params => { if (!isNaN(params.rt)) { c ...

Exploring the Power of Angular's Redux Implementation with Lazy Loading Strategy

Implementing Redux with Angular has been incredibly beneficial for me, but I am curious about how lazy loading can be incorporated alongside it. Can these two techniques work well together? ...

Attempting to verify if a function is being invoked within a subscription, but finding that it never gets activated

I have a method that needs to be tested when called in an ngOnInit. Specifically, I want to ensure that when the ngOnInit is triggered, this.anotherService.methodToCall() is executed and verify what parameters it is called with. However, despite my effort ...

Aggregate the data chunks in the antd table into groups

I've been struggling to find a solution for this specific issue. My goal is to group the data in my table based on a particular field, but I need it to be styled as depicted in the image linked below. https://i.stack.imgur.com/OsR7J.png After looking ...

Creating a View-Model for a header bar: A step-by-step guide

I am looking to develop a View-Model for the header bar using WebStorm, TypeScript, and Aurelia. In my directory, I have a file named header-bar.html with the following code: <template bindable="router"> <require from="_controls/clock"></ ...

Problem with Invoking method of parent component from child component in Angular 4

Despite having all my event emitters set up correctly, there's one that seems to be causing issues. child.ts: @Component({ ... outputs: ['fileUploaded'] }) export class childComponent implements OnInit { ... fileUploaded ...

What specific data types should I be using for the $location and $stateParams services?

Currently in the process of redeveloping my AngularJS application (version 1.5) using TypeScript. Can you advise on the types required for injecting the services $location and $stateParams? ...

Develop an extensive Typescript and React shared library

Trying to develop a shared React and Typescript library has been quite challenging. Configuring the project workspace to work on both the library and application simultaneously has proven to be more difficult than anticipated. project ├─ app │ ├ ...

Angular and Ngrx: The optimal approach for choosing a value within a component and a function

While browsing through this Stack Overflow thread, I stumbled upon a question similar to mine. However, I'm curious if the solution provided in the comments is still considered the best practice in today's standards. Here's where I stand: ...

Invalid action has been dispatched by the effect:

In my project, I am using Angular 7.1.4. This is an excerpt from my effect code: @Injectable() export class LoginEffects { constructor(private actions$: Actions, p ...

Navigating through Angular using Typescript can sometimes lead to uncertainty when working with return data. This is where the

How do you handle a request with uncertain data and type checking? For instance, if you are making an HTTP call to an API where various data can be returned, but your component requires a specific data structure defined by an interface. Here's a sim ...

One-of-a-kind data connection

I'm facing a challenge with data-bindings that I can't quite crack. It seems like my lack of expertise in the Angular domain might be the root cause. If you have a solution, I would greatly appreciate it if you could provide a brief explanation ...

The constant issue persists as the test continues to fail despite the component being unmounted from the

import { render, screen } from '@testing-library/react'; import '@testing-library/jest-dom/extend-expect'; import { act } from 'react' import Notifications, { defaultNotificationTime, defaultOpacity, queuedNotificationTime, fa ...

The function cannot be found within the specified file

Snippet.ts export class Snippet { public async processData(data): Promise<any> { //processing logic } } Snippet.spec.ts //correctly imported Snippet class describe('testing', async () =>{ it('ProcessData test ...

Issues with Karma Testing: None of the Tests Executed Successfully

I am currently enrolled in the Angular Fundamentals course presented by Jim Cooper on Pluralsight. Despite following the course meticulously, using the same versions, and replicating the code exactly, I am facing an issue with running my Karma tests. Belo ...

The functionality to verify the presence of a child element is not functioning correctly when using

Trying to determine the existence of a child, I have created a new Firebase list observable and also attempted with an object observable. Upon creating the observable, I verify if it exists or not; however, it always returns false. Database Structure: {R ...