0

I have 2 functions one func1 and func2, I need to execute the func2 only after func1 will execute. Here the code below

home.component.ts

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})

export class HomeComponent implements OnInit {

 constructor() { }

 ngOnInit() {
    this.func1();
    this.func2();
 }

 func1(){
    console.log('function1')
 }

 func2(){
    console.log('function2')
 }
}
sibabrat swain
  • 1,277
  • 8
  • 20

2 Answers2

1

There are a few things you need to know here. If your func1 is not an asynchronous function then you don't need to do anything as the func2() will only execute after completion of func1(). But if the func2() is an asynchronous function where you do some HTTP operation then you need to use call back function.

Let me show you.

Type - 1 (using async and await)

async ngOnInit() {
  await this.func1();
  this.func2();
}

func1(){
  this.func1().then(() => {
    this.func2();
  })
}

func2(){
  console.log('function2')
}

Type - 2 (using then)

ngOnInit() {
  this.func1().then(() => {
    this.func2();
  })
}

func1(){
  return new Promise((resolve, reject) => {
     return resolve(true);
  });
}

func2(){
  console.log('function2')
}

Type - 2 (Simpler one)

function func2(){
  func1()
  // now wait for firstFunction to finish...
  // do something else
};

There are multiple ways to handle this situation depending on first function.

sibabrat swain
  • 1,277
  • 8
  • 20
0

I think, this will solve your problem.

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})

export class HomeComponent implements OnInit {

 constructor() { }

 ngOnInit() {
    this.func1();
 }

 func1(){
    console.log('function1')
    this.func2();
 }

 func2(){
    console.log('function2')
 }
}