【问题标题】:How to call a function after other function in angular 8如何在角度8中的其他函数之后调用函数
【发布时间】:2020-09-16 03:48:04
【问题描述】:

我有 2 个函数 func1 和 func2,只有在 func1 执行后我才需要执行 func2。下面是代码

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')
 }
}

【问题讨论】:

标签: angular typescript


【解决方案1】:

这里有几件事情你需要知道。 如果你的 func1 不是一个异步函数,那么你不需要做任何事情,因为 func2() 只会在 func1() 完成后执行。但是,如果 func2() 是一个异步函数,您可以在其中执行一些 HTTP 操作,那么您需要使用回调函数。

让我告诉你。

Type - 1(使用 async 和 await)

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

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

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

类型 - 2(使用 then)

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

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

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

Type - 2(更简单的一种)

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

根据第一个功能,有多种方法可以处理这种情况。

【讨论】:

  • 向 ngOnit 添加异步是不好的做法
  • @Flightdoc5242 只要你知道stackoverflow.com/a/56092621/9739044的含义就没有问题@
  • @Flightdoc5242 请避免对答案投反对票,而是评论您的想法。
【解决方案2】:

我想,这会解决你的问题。

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')
 }
}

【讨论】:

    猜你喜欢
    • 2020-09-05
    • 2017-03-09
    • 1970-01-01
    • 2018-06-09
    • 1970-01-01
    • 2021-05-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多