Ensure you pause for the HTTP request to finish in an Angular 4 service

I have a question regarding Angular services, specifically promises and observables, as I am new to them. On my login page, I have a button that, when clicked, should validate the user and generate a token before redirecting to the Home page. However, currently what is happening is that the page redirects before the token is assigned by the service function call asynchronously.


App Data Service


    import { Injectable } from '@angular/core';
    import { HttpClient,HttpHeaders } from '@angular/common/http';
    import 'rxjs/add/operator/map';
    import 'rxjs/add/operator/mergeMap';
    import 'rxjs/add/operator/toPromise';
    @Injectable()
    export class AppDataServiceService {
      tokenGenerated:any='';
      constructor(private http: HttpClient) { 

      }

      getData(){
        console.log("Started.. in service");
         this.http.get('http://host/url').toPromise()
         .then(this.extractData);

      }
      private extractData(res: Response) {
        console.log("completed.. in service");
        this.tokenGenerated=res;
        return res;
    }

    }
---------------------------------------------------
   Login Component

    import { Component, OnInit } from '@angular/core';
    import { AppDataServiceService } from '../app-data-service.service';
    import { Router } from '@angular/router';

    @Component({
      selector: 'app-login-component',
      templateUrl: './login-component.component.html',
      styleUrls: ['./login-component.component.css']
    })
    export class LoginComponentComponent implements OnInit {

      constructor(private dataService:AppDataServiceService,private router:Router) {

       }

      ngOnInit() {
      }

      submit(){
        this.dataService.getData();
        console.log('after executing service');
        this.router.navigate(['/view']);
      };

    }
-------------------------------------------------------------
   Login HTML
   
<div class="container">
  <label><b>Username</b></label>
  <input type="text" placeholder="Enter Username" name="uname" >

  <label><b>Password</b></label>
  <input type="password" placeholder="Enter Password" name="psw" >

</div>

<input type="button" (click)='submit()' value="Login"  name="submit"/>

Console output in browser:

Started.. in service

after executing service

completed.. in service

I need assistance in making the HTTP call synchronous using promises. Could you guide me on the correct implementation?

Answer №1

Make sure to update your service to return a promise or Observable, which should be subscribed to in the component.

If you don't do this, the component won't know when the asynchronous code has completed, causing it to display the log statement immediately.

Modify the service like this:

fetchData(){
    console.log("Fetching data from server..");
    return this.http.get('http://host/url').toPromise()
        .then(res => this.extractData(res));
}

Then in the component:

onSubmit(){
    this.dataService.fetchData().then(() => {
        console.log('Service execution completed');
        this.router.navigate(['/view']);
    });
}

Answer №2

To incorporate synchronous http request, follow the code snippet provided

var httpRequest = new XMLHttpRequest();
httpRequest.open('GET', "https://yourdomain/api", false);  
httpRequest.send(null);
const responseData = JSON.parse(httpRequest.responseText); 

If Dependency Injection using HttpClient is not feasible, this method should be used sparingly and only when necessary.

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

Discovering an entry that lacks a specific value within an array in the records

Currently, I am utilizing sequelize along with typescript in a node environment (with a postgresql database). Here is the model that I have defined: id: number, someField: string, arr1: number[], arr2: number[] My objective is to retrieve all records wher ...

After triggering an action, I am eager to make a selection from the store

To accomplish my task, I must first select from the store and verify if there is no data available. If no data is found, I need to dispatch an action and then re-select from the store once again. Here is the code snippet that I am currently using: t ...

Troubleshooting: @HostListener for window scroll event not functioning as expected

Having trouble creating a sticky header that stays fixed when scrolling down in an Angular 4 application. The scroll event is not being detected. The header is located in the layout component, while the content I want to be scrollable is placed in the rou ...

Challenges encountered while integrating the Ngrx Store service with my component

Following a user's attempt to address an issue related to my post on Stackoverflow titled "My stackoverflow old post", I am currently working on implementing the Ngrx store using the guidelines provided on Ngrx store github. This will assist me in han ...

Add an asterisk before each line of comment when working in a TypeScript file using the VS Code IDE

Within my VS Code workspace, I am using the Typescript language and would like to format my comments across multiple lines with a specific style (look out for the star character) /** *@desc any text * any text */ However, when I attempt to write a comm ...

Setting up routing in Angular using a fixed string value alongside a dynamic parameter

I am trying to configure routing in a unique way by having URLs like hotel-123, hotel-456, where 'hotel' is constant and the number following it represents a parameter 'code'. Below is my app.routes.ts configuration: import { Routes } ...

Make Ionic 2 Navbar exclusively utilize setRoot() instead of pop()

When navigating to a different page, the ion-navbar component automatically includes a back button that uses the pop() method to return to the previous page. Is there a way to modify this behavior so that it utilizes the setRoot() method instead of pop(), ...

What is the process for generating a watermark directive in angularjs?

My application utilizes a jQuery script for watermarking textboxes. I created a directive to easily apply this watermark to input elements, but it's not functioning as expected. While debugging, I can see the watermark being added, but once the UI fin ...

Unable to establish a connection with the websocket server

I set up a websocket server on my host at <www.example.com>, but for some reason, the client is unable to connect to it. Here is the code : Server.js : const ws = new require('ws'); const wss = new ws.Server({noServer: true}); const htt ...

Is there a way to resolve the scrolling problem on Google Maps?

When using the Google Maps V3 API, an issue arises where zooming out on the map using the scrollbar also causes the page to scroll along with it. This can be quite frustrating and so far I have not been able to find a way to disable this scrolling behavi ...

What is the best way to determine if an element is out of the viewport during scrolling?

One of my tasks is to detect whether an element is within the viewport as the user scrolls. If the element is outside the viewport, I apply a class that affixes the element to the top. The function I employ to determine if the element is outside the viewp ...

Confused within the realm of javascript's scope

Hello, I'm looking for some assistance with the code snippet provided below. My goal is to call the function doTheSlide() from within the slide event function in JavaScript. However, I seem to be struggling with understanding scope in JS. Could someo ...

Chrome Web Store issues an overly stringent warning for accessing a public API

A new Chrome Extension called FrontPage was recently created, utilizing the New York Times API. The extension sends an AJAX request to the API and receives a JSON response. However, to make this possible, specific permissions need to be set in the manifes ...

When using ngModel, the Tinymce Angular 2+ templates do not initially replace values, whereas they do when templates are inserted by the user

In my Angular 7 app, I am utilizing the TinyMCE editor component. When I insert a template variable into the editor: <span class="data-variable">${variable_name}</span> The variable gets replaced successfully with a value from the `template_r ...

Preventing duplicate results in AJAX and SQL

I'm facing an issue with my ajax request and PHP script - when I click the button, the results are duplicating. Here is the HTML AND JS: $("#more-news").click(function(e) { e.preventDefault(); $.ajax({ type: "GET", url: ...

Using jQuery to locate a particular number and substitute it with a particular string

On my website, I have a food menu that allows users to customize their meat selection. For example: shawarma: pita: $10 Baguette: $12 Plate: $17 steak: pita: $20 Baguette: none Plate: $35 The issue arises when some menu items do not include one of the o ...

Tips for incorporating runtime configuration into an Angular module and effectively leveraging it

After setting up Apollo Angular, I encountered a challenge in src/app/graphql.module.ts src/app/graphql.module.ts import { NgModule } from '@angular/core'; import { APOLLO_OPTIONS } from 'apollo-angular'; import { ApolloClientOptions, I ...

Optimizing Performance: Placing Laravel and VueJS instances and components strategically

I am unsure about the best approach for implementing Vue in my project which is not an SPA. Should I create a Vue instance for every component or have a single Vue instance managing all components? ... <body> .... <div id="nav">... .... <d ...

Automatically update the div every few seconds and pause when it has loaded successfully

I am facing a challenge in creating a div that refreshes automatically every 10 seconds, but stops when it successfully loads. Here is the jQuery script I have developed: <script type="text/javascript"> $(document).ready(function(){ var j = jQuer ...

Challenges faced when subscribing to global events in JavaScript

I have some questions about the JavaScript code snippet below: What does .events.slice(-1)[0][0] signify? Similarly, could you explain the purpose of nodes_params += "&ns=" + GLOBAL_EVENT + "," + start_from + ",-,-";? Could you elaborate on what is m ...