Waiting for the HTTP response in Ionic 2

I've been trying to figure out how to make my code wait for the http request before moving on. The reason I need this is because I rely on the response to populate some variables in the HTML.

So,

Question 1: Do I really need to create a Service to make an HTTP request and return a Promise/Observable?

Question 2: In my code, is there a way to make it wait for the response without creating a separate service?

let link = 'http://working url';
      let headers = new Headers({
          'Content-Type': 'application/x-www-form-urlencoded',
          'Accept': '*/*'
      });

      let options = new RequestOptions({headers: headers});

      this.http
          .post(link, this.loginString, options)
          .map(res => res.json())
          .subscribe(
              data => {
                  let response = JSON.parse(data);
                  if(response.Successfull){
                      if(response.ReturnObject.length>0){
                          this.orders = this.orderJson(response.ReturnObject);
                          this.ordersWithoutGroup = response.ReturnObject;
                          this.empty = false;

                      }else{
                          this.orders= [];
                          this.empty= true;
                      }
                  }

          }, err => {
              this.showAlertError();
          }, () => {
              this.loadingPopup.dismiss()

          });
}

Appreciate any help you can provide.

EDIT 1: HTML:

<ion-content class="stable-bg" scroll="true">
 <div class="item-input-inset">
     <label class="item-input-wrapper">
         <i class="icon ion-ios-search placeholder-icon"></i>
         <input type="text" placeholder="Search Orders" ng-model="search">
     </label>
 </div>
 <ion-list *ngIf="orders !== null" ng-repeat="(date, group) in orders">
     <ion-item class="item-divider">{{ date }}</ion-item>
     <ion-item class="item-icon-left item-icon-right" ng-repeat="order in group" (click)="goToDetail(order.ID)">
         <div ng-show="order.DocumentNumber.indexOf(search) >-1 || !search ">
             <i class="icon ion-card"></i>
             <div>Nº {{ order.DocumentNumber }}
                 <span class="gray pull-right">{{ order.time }}</span>
             </div>
             <i class="icon ion-ios-arrow-right"></i>
         </div>
     </ion-item>
 </ion-list>
 <div ng-show="empty">
     <div class="card">
         <div class="item item-text-wrap ion-information-circled" (click)="check()">At the moment there isn't any order to
approve.</div>
     </div>
  </div> 
</ion-content>

More code related to the .ts file:

import { Component , OnInit, Injectable} from '@angular/core';
import { NavController, AlertController, LoadingController } from 'ionic-angular';
import { Http, Headers, RequestOptions} from '@angular/http';
import * as moment from 'moment';


@Injectable()
@Component({
selector: 'page-orders',
templateUrl: 'orders.html'
})
export class OrdersPage implements OnInit{

    orders: any;
    loginString: any;
    empty: boolean;
    ordersWithoutGroup: any;
    loadingPopup: any;;

constructor(public navCtrl: NavController,private alertController: AlertController,  private http: Http, private loadingCtrl: LoadingController) {
 this.loadingPopup = this.loadingCtrl.create({
  content: 'Loading orders...'
});

// Show the popup
this.loadingPopup.present();
  this.orders= {}
  this.loginString = localStorage.getItem("Auth");

}

ngOnInit() {
        this.getOrders();
    }

EDIT 2: Check out my console.log of the orders: https://i.sstatic.net/CCEPU.png

Answer №1

Query #1: Is it necessary to create a Service for making an http request and returning a Promise/Observable?

The need for a Service depends on your specific implementation. Executing http.post() directly from the same component may not have any technical impact. However, utilizing a common service offers certain advantages such as -

  1. Modular code - Services are designed to handle data retrieval while components focus on component-specific operations.

  2. Reusability - A single service can be reused across multiple components with similar behavior, allowing for parameter-based manipulations.

In my code, is there a way to make it wait for the response without creating a separate Service?

The purpose of .subscribe() method is precisely for handling such scenarios. You can move all code that requires the response within this subscription block.

If you need HTML variables, I can suggest two solutions:

  1. Utilize ngIf in the component's UI tags to conditionally display content based on the availability of the data variable. For example,

    <p *ngIf="_data !== null">Show data : {{_data}}</p>
    . This approach eliminates the need to wait for data loading, updating the UI automatically upon data arrival.

  2. Load all data on the previous page, then navigate to the current page using navParams in the .subscribe() block before rendering. (This suggestion aims at quick modifications in your existing code.)

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

Having difficulty specifying the class type in Typescript

I am currently working on defining a 'Definition' type in Typescript. In this case, a Definition could be either a class constructor or an object. Here is the code snippet that illustrates my approach: if (this._isConstructor(definition)) { r ...

Step-by-step guide on integrating a custom JS file into an Angular component

Trying to grasp Angular, I embarked on adding some JavaScript logic to one of my components from a separate JS file. While following advice from a similar query (How to add custom js file to angular component like css file), it seems I missed something cru ...

Enabling withCredentials in Angular 6 for every HttpClient request is crucial for maintaining consistent authentication and

Is there a method to set { withCredentials: true } as the default for every httpclient call, instead of having to add it manually each time? import { HttpClient } from '@angular/common/http'; ... constructor(private httpclient: HttpClient) { } ...

Utilizing type maps within nested objects in Typescript: A comprehensive guide

Initially, a type is established that connects enum keys with specific types: enum MyEnum { A, B } type TypeMap = { [MyEnum.A]:string, [MyEnum.B]:number } interface ObjInterface<T extends keyof TypeMap> { obj: T, objData: Ty ...

Angular 6 - Build a dynamic single page housing various applications within

I am faced with the task of developing multiple applications using Angular 6. Each application will have its own set of components, services, and more. However, there is also a need for shared services, components, directives, and other elements that will ...

Utilize the ES6 spread operator to send information across components as props

ChildComponent.ts export class ChildComponent implements OnInit { @Input() name?: string; @Input() email?: string; // Many more properties constructor() {} ngOnInit(): void {} } ParentComponent.ts export class ParentComponent implements OnInit ...

The Angular application will only display updated dynamic content upon refreshing the page

I am utilizing a factory to access my server-side data, using $routeParams to pass the id in the server request. Initially, everything functions correctly, but issues arise after the first run through the program. Here is a snippet of my code: Controller: ...

Having constant problems with ngModel twoway binding. Any suggestions on how to successfully bind to a property in order to update an api link?

I am attempting to implement two-way binding in order to dynamically change the API endpoint when a button is clicked. The value attribute of the button should be used as part of the API URL string. I tried following an example in the Hero Angular App, bu ...

I'm seeing an issue where my SafeResourceUrl is being displayed as undefined within a function of the identical class

export class ClassName implements OnInit { url: string = "{{'content.url' | translate}}"; urlSafe: SafeResourceUrl; constructor(public sanitizer: DomSanitizer, private translate: TranslateService) { } ngOnInit() { ...

Which properties are missing from this type?

I received the following message: Issue with 'Motorvoertuig' class implementing 'Voertuig' interface. Error: Type 'Motorvoertuig' is missing properties from 'Voertuig': toonMerk, wieIsDeEigenaar However, the ...

Getting the value from an array of objects in React Redux Toolkit

Task: const postsData = useSelector((state: RootState) => state.postsSlice.posts); { postsData?.map((post) => { return ( <PostCard key={post.id} title={post.title} description={post.body} user={post.use ...

Dealing with Promise Wrapper Already Declared in TypeScript Return TypeMismatch

Here is a snippet of TypeScript code I am working with: type Chain = 'eth' export type ApiMethods = { getToken: { path: 'tokens/' (args: { chain: Chain tokenAddress: EthereumAddress }): string } getRank: ...

The HTTP POST request is successful with a 200 status code, however, it

Being relatively new to HTTP, I am attempting to send a post request on my parents' restaurant website to register a new user from my app. The website in question is this (in Spanish): Based on my understanding, the post request contains the followi ...

Is it possible to deduce the types of a particular value based on an interface that is provided as a generic parameter?

As a newcomer to TypeScript, I may be approaching this issue the wrong way. I am curious if there is a generic type that can handle an interface like {[key: string]: string | boolean} and allow for knowing the specific type of any value inside the consumin ...

Access the document within the Angular Material File Selection feature

I have implemented a Material file selection feature in my project. The code snippet below shows how I am doing it: <label for="uploadPicture" class="upload-file"> <mat-icon>add_a_photo</mat-icon> </label> <input type="file" ...

React's setState is not reflecting the changes made to the reduced array

I am currently working on a custom component that consists of two select lists with buttons to move options from the available list to the selected list. The issue I am facing is that even though the elements are successfully added to the target list, they ...

Utilizing OKHTTP to submit user-generated data and fetch JSON response to validate success

I've been pondering the best way to approach this task. After thoroughly reviewing the documentation for OKHTTP, I believe I have a plan for handling it, but I'm still uncertain. My strategy involves having users input three fields (Username, Pa ...

Learn how to securely download files from an Azure Storage Container using Reactjs

I'm currently working on applications using reactjs/typescript. My goal is to download files from azure storage v2, following a specific path. The path includes the container named 'enrichment' and several nested folders. My objective is to ...

The Vue 3 Composition API - The property retrieved by setup() "is accessed during rendering but is not defined in the instance."

I've been experimenting with Vue 3's Composition API by creating a small in-app message console, but I'm having trouble pinpointing the error in my code. When rendering this component, the state is being accessed during render (in the loop), ...

Filtering through an array object with PrimeNG

Is it feasible to utilize an array of objects for filtering data in a table? I'm currently using Angular 6 and PrimeNG 7. This is how my p-table appears: <p-table #table class="ui-table ui-table-responsive" [value]="arrays" [columns]="cols" > ...