Run a second function once the first function in Angular has been executed

I have a method called createCal within the ngOnInit function. After createCal is executed, I want to run createDefault() after the loop has been executed three times. Following that, other codes should execute that come after createCal. I am receiving a warning message saying that 'await' has no effect on the type of this expression.

 ngOnInit() {
    this.createCal();
    ..
    }
    
     async createCal()
      {
        let response=await this.commonService.getAllList().toPromise();
        if(response?.length==0)
        {
          let res=await this.createDefault();
        }
      }
    
    
    
     createDefault()
      {
        let defaultList=['Test 1','Test 2','Test 3'];
        for(let i=0;i<defaultList.length;i++)
        {
          if(defaultList[i])
          {
            let Json =  {
              Id: defaultList[i],
            }
            this.commonService.create(Json).subscribe(async (x: any) => {  
         
            }) 
          }
        }
      }

Answer №1

I'm a bit confused about your intentions...

It seems like you also need to make the createDefault function asynchronous.

ngOnInit() {
    this.createCal();
    ..
    }
    
     async createCal()
      {
        let response = await this.commonService.getAllList().toPromise();
        if(response?.length === 0)
        {
          let res = await this.createDefault();
        }
      }
    
    
    
     async createDefault()
      {
        let defaultList=['Test 1','Test 2','Test 3'];
        for(let i=0;i<defaultList.length;i++)
        {
          if(defaultList[i])
          {
            let Json =  {
              Id: defaultList[i],
            }
            // It's recommended to use "toPromise" here as well if you want to wait...
            this.commonService.create(Json).subscribe(async (x: any) => {  
         
            }) 
          }
        }
      }

Note

toPromise is deprecated. The new function is lastValueFrom. Use it like this:

...
async createCal()
      {
        let response = await lastValueFrom(this.commonService.getAllList());
        if(response?.length === 0)
        {
          let res = await this.createDefault();
        }
      }
...

Answer №2

The error you're encountering is due to the fact that the createDefault function is not asynchronous. It's recommended to choose either Promises or Observables for a more cohesive approach.

Here's a way to achieve the desired outcome without Promises, leveraging rxjs:

ngOnInit() {
  this.commonService.getAllList().pipe(
    filter(response => response?.length === 0), 
    switchMap(() => {
      const defaultList = ['Test 1','Test 2','Test 3'];
      const jsonObjects = defaultList.map(id => ({Id: id}));

      return combineLatest(
        jsonObjects.map(json => this.commonService.create(json))
      );
    }),
  ).subscribe()
}

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

404 Error: The requested API endpoint seems to have gone missing, as the URL cannot be found

I encountered a 404 not found error when attempting to create a new customer in my angular 10 application. Oddly, the API method works flawlessly in Postman but fails when called from the angular client. The cause of this issue is eluding me Using Postman ...

Creating an HTTP gateway with Observables

When dealing with multiple requests, I need to pause them until the authentication of the http request has been confirmed. Essentially, I require an http gate where some requests can pass without authentication, while others need to wait for the token to b ...

Angular 2 Routing 3.0: Paying Attention to Letter Case

let routesList: Routes = [ { path: 'x', component: xComponent }, { path: 'y', component: yComponent }, { path: 'zComponent', component: zComponent } ]; When entering "x" in the URL, it navigates to the component page. Ho ...

A viewless Angular 2 component

Is it feasible to utilize Angular 2 without the need for a template or an @View? I am exploring alternative methods akin to the example shown below: Angular 1 index.html <div ng-controller="appcontroller"> <div ng-class="{active: isActive()}"& ...

Exploring the functionality of surveyjs in conjunction with react and typescript

Does anyone have any code samples showcasing how to integrate Surveyjs with React and TypeScript? I attempted to import it into my project and utilized the code provided in this resource. https://stackblitz.com/edit/surveyjs-react-stackoverflow45544026 H ...

What could be causing TypeScript to display errors in unexpected locations while inferring inner types?

I encountered a rather intricate issue that's challenging to sum up in a brief title, my apologies for that. I devised a function that accepts a generic params type and returns a result type constructed from the params type. It utilizes string literal ...

Having trouble selecting all checkboxes in the tree using angular2-tree when it first initializes

My goal is to have all checkboxes auto-checked when clicking the "feed data" button, along with loading the data tree. I've attempted using the following code snippet: this.treeComp.treeModel.doForAll((node: TreeNode) => node.setIsSelected(true)); ...

Angular HTTP requests are failing to function properly, although they are successful when made through Postman

I am attempting to send an HTTP GET request using the specified URL: private materialsAPI='https://localhost:5001/api/material'; setPrice(id: any, price: any): Observable<any> { const url = `${this.materialsURL}/${id}/price/${price}`; ...

subscribing to multiple observables, such as an observable being nested within another observable related to HTTP requests

Hello, I recently started learning Angular and I am facing a challenge with posting and getting data at the same time. I am currently using the map function and subscribing to the observable while also having an outer observable subscribed in my component. ...

Attempting to retrieve data from cloud Firestore utilizing keyvalue in Angular

My database stores user information under the 'users' collection. I can access this data using the following code: In my service: users$ = this.afs.collection<Users[]>('users').valueChanges(); In my component: public users = t ...

Unable to install a specific commit of an angular library from GitHub using npm

While utilizing Angular 2.0.0-beta.15, I encountered the inability to upgrade it. Thus, I had to search for a specific commit from the ng2-dnd library on GitHub. Upon locating a compatible commit for version 2.0.0-beta.17: "ng2-dnd": "git://github.com/ak ...

What is the process of adding an m4v video to a create-next-app using typescript?

I encountered an issue with the following error: ./components/Hero.tsx:2:0 Module not found: Can't resolve '../media/HeroVideo1-Red-Compressed.m4v' 1 | import React, { useState } from 'react'; > 2 | import Video from '../ ...

What is the reason a type is able to cast to an indexed collection when it is inferred, while an explicit type that seems identical is

I am puzzled by why my inferred types are considered as instances of my more general collection type while my explicit types are not. My goal was to: Have a specific part of my application work with tightly defined collections (e.g., IParents vs IBoss ...

Allow Nest.js server to receive binary files in the request body

Is there a way to retrieve the uploaded binary file data from the browser? While the Nest.js server application functions correctly with Postman, it throws a 400 error when the request is sent from the Google Chrome/Angular application. Any ideas on how ...

Retrieving desired route in Angular 2 RC5 within canDeactivate function

Is there a way to retrieve the desired route within the CanDeactivate guard of the Angular 2 RC5 router? I came across a solution for a similar scenario involving CanActivate (CanActivate), but it doesn't seem to apply to CanDeactivate. My specific s ...

Is your pure function component not receiving or responding to input props correctly?

Here is my code snippet: const actionCreators = { action: AppReducer.actionCreators.action } interface GlobalState { user: Model.User | null; } interface InputState { setStashBarWidth(width: number); stashWidth: number; } const Header = ...

Issues with IonPicker displaying incorrect values

In my Ionic App, I am using the ion-picker component to display the selected text from an array of options. Although everything seems to be working fine and the console.log accurately displays the index value, there is a strange behavior when it comes to s ...

Verify your identity with Azure AD B2C within a NativeScript Angular application

Is there a way to integrate Azure AD B2C authentication into a NativeScript Angular mobile app? I'm looking to create a mobile application that integrates with my current web application for authentication utilizing Azure AD B2C. ...

How can one correctly cast or convert an array of objects to the interface that extends the objects' parent interface in Typescript?

Question: How can I optimize the usage of method sendItemIdsOverBroadcastChannel to reduce message size? interface IItemId { id: number; classId: number; } interface IItem extends IItemId { longString: string; anotherLongString: string } inte ...

Using Typescript, invoke functions within an object by specifying a string key

I am looking for a way to call methods in an Object using string keys, but I'm facing issues with it. Could someone provide some solutions for this? type Methods = { foo?: (v: string) => string; bar?: (v: number) => number; baz?: (v ...