"Alert in Javascript executing prematurely prior to initiating the function for sending a get request

private validateURL(url: string) {
    let isValid = false;
    this.$http.get(url).then(
        (data) => {
            console.log('success');
            isValid = true;
        }
    ).catch( 
        (reason) => {
            console.log('failure ' + reason);
            isValid = false;
        }
    ).then(
        () => {
            return isValid;
        }
    )
}
private checkURL() {
    if (!this.validateURL(url)) {
        alert('Incorrect URL');
        return false;
    }
}

The issue is that the alert in the if statement is being triggered before the validateURL function is called. How can I ensure that the function is invoked first?

Answer №1

Employ a promise to handle URL validation. The extended version, featuring the console.log statements, looks like this

private checkURLValidity(url: string) {
    return new Promise((resolve, reject) => {
        this.$http.get(url).then(
            (data) => {
                console.log('success');
                resolve();
            }
        ).catch(
            (reason) => {
                console.log('failure ' + reason);
                reject();
            }
        );
    }

private anotherMethod() {
    this.checkURLValidity(url).catch(){
        alert('Invalid URL provided');
        return false;
    }
}

Alternatively, opt for the concise version and directly utilize the promise returned by $http

private verifyURL(url: string) {
    return this.$http.get(url);
}    

private anotherMethod() {
    this.verifyURL(url).catch(){
        alert('Invalid URL provided');
        return false;
    }
}

Answer №2

Uncertain about the ts syntax, but here's a potential solution:

private checkValidURL(url: string) {
  return this.$http.get(url)
    .then(() => true, () => false);
}
private executeFunc() {
  this.checkValidURL(url)
    .then(isValid => {
      console.log(isValid ? 'URL is Valid' : 'URL is Invalid');
    });
}

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

Develop an rxjs pipeline that merges values according to their type prior to executing them in an async manner using concatMap

In my code, there's an eventStream that deals with different types of events and sends them to the server via HTTP. import { from, Observable } from 'rxjs'; import { concatMap } from 'rxjs/operators'; type Update = number[]; inte ...

Expanding interfaces dynamically in Typescript

Currently, I am facing a challenge while attempting to integrate an existing React Native module equipped with the following props: useComponent1: boolean useComponent2: boolean This is how the implementation looks like: render(){ if(useComponent1){ ...

Tips for executing numerous asynchronous tasks in Ionic 3 and closing a loader once all tasks are completed

Currently, I am in the process of developing an Ionic 3 application that offers the feature to cache a list of articles content on demand. The implementation involves utilizing Storage which employs promises for its operations. The code snippet I have wri ...

Issue detected in rxjs-compat operator's shareReplay file at line 2, column 10:

I've encountered an issue with the angular material spinner I'm using in my project. The error message is as follows: ERROR in node_modules/rxjs-compat/operator/shareReplay.d.ts(2,10): error TS2305: Module '"D:/ControlCenter/ofservices ...

Exploring through angular.js with the use of identifiers

In my data, I have two JSON objects: all_users "all_users": { "4":{ "user_id":4, "user_name":"Miranda" }, "7":{ "user_id":7, "user_name":"seconduser" } And tickets "tickets": [{ "ticket_id" : 12, "created_by" : ...

Unlock the power of Angular ViewChildren to access and manipulate SVG elements efficiently

I have an SVG file loaded as an object: <object data="assets/img/states.svg" type="image/svg+xml" id="map"></object> This SVG includes a large PNG map along with several rect and text elements. <rect y="224.72084" x="644.87109" ...

Make simultaneous edits to multiple cells in IGX GRID for Angular

Is it feasible to edit multiple cells in the same column simultaneously within igx grid Angular? I would like for the changes made within each cell to be displayed at the same time. Editing many cells all at once is a valuable feature! ...

Steps for building a custom component using MUI as a foundation

My current approach: import React from "react"; import {useHistory} from "react-router-dom"; import {Button, ButtonProps} from "@mui/material"; type Props = { label?: string } & ButtonProps; export const NavBackButton = ...

Leveraging the AngularJS promise/defer feature alongside the Quickblox framework, learn how to efficiently upload images and subsequently upload public URLs to a custom

I am currently developing an application that requires users to upload 5 images of themselves. Using a backend-as-a-service platform like Quickblox, I have to create and upload blob files individually. Once each image is uploaded, I receive a success call ...

Angular Error: Trying to access a property on an undefined variable

I'm currently having an issue with assigning data from an API to my Angular component file. Whenever I try to assign the data to my object variable, I receive an error stating: "cannot set property of undefined." Below is the relevant code snippet: C ...

Removing empty options from a select dropdown in Angular 9

In the process of working with Angular 9, I am currently in the process of constructing a dropdown menu that contains various options. However, I have encountered an issue where there is a blank option displayed when the page initially loads. How can I eli ...

An obstacle encountered when implementing feature module services in a controller for a Nest JS microservice

Recently, I developed a feature module named "user" which includes a controller, model, and services to interact with my postgres database. Despite setting up everything correctly, I encountered an error when trying to call userService from the feature mod ...

Ignore verification of unused parameters

In my typescript project compilation process, I make use of the noImplicitAny option to ensure that I specify the types for variables and arguments. However, there are instances where I have unused arguments. For instance: jQuery.ajaxTransport("+*", func ...

Elevate the scope analysis for a function within the Jasmine framework

I have written a few functions within the app component. I am experiencing an issue with increasing coverage in the summary for these component methods. The test cases are functioning correctly, but some lines are not being accounted for in the coverage s ...

Guide on showing a component exclusively for iPads with React and TypeScript

I need help displaying an icon only in the component for iPad devices, and not on other devices. As a beginner in coding for iPads and mobile devices, I am unsure how to achieve this specific requirement for the iPad device. Below is the code snippet tha ...

mysterious supplier factoryprovider <- factory <- angular js controller

I'm encountering an issue with injecting dependencies from a service to a controller. Despite adding it, I keep receiving the following error: Unknown provider: websiteFactoryProvider <- websiteFactory <- listCtrl My main goal is to display ...

Encountering problem with React Typescript fetching data from Spring Data REST API: the error message "Property '_embedded' does not exist" is being displayed

I am currently working on a React application that utilizes Typescript to fetch data from a Spring Data REST API (JPA repositories). When I make a specific request like "GET http://localhost:8080/notifications/1" with an ID, my JSON response does not pose ...

Differentiating Service Class and Typescript Class in Angular 6

I am looking for a detailed explanation of service classes in Angular. From my perspective, both service classes and typescript classes serve the same purpose. So, what sets them apart from each other? ...

Leveraging require.ensure within webpack

I've been tackling a project with angular-webpack and I'm interested in using require.ensure() along with it. var app= angular.module('app', ['pascalprecht.translate', 'react', ...

Angular 11 now includes the ability to implement lazy loading for modules

Here is the configuration of my app-routing.module.ts: const routes: Routes = [ { path: 'login', component: LoginComponent }, { path: '', canActivate: [AuthGuard], component: HomeComponent, children ...