首页 > 解决方案 > Angularjs打字稿等待函数结束以运行另一个函数

问题描述

我正在 Angular CLI 中开发一个应用程序,我只想在插入后获取一个列表。经过一些研究,我已经阅读并尝试了很多东西(observer / promise / async / setTimeout / ...),但找不到正确的答案。我可能已经不远了。

这是我现在拥有的代码。在 insertStatut() 中,我正在执行插入 (service.insertStatuts()) 并在 getStatuts() 之后更新列表。

这是我的组件中的代码:

import { Component, OnInit } from '@angular/core';
import { MatStatutService } from '../mat-statut.service';
import { MatStatut } from '../matStatut';

@Component({
  selector: 'app-mat-statut',
  templateUrl: './mat-statut.component.html',
  styleUrls: ['./mat-statut.component.css']
})
export class MatStatutComponent implements OnInit {
  private statuts: MatStatut[];
  private inStatut = new MatStatut;

  constructor(private service:MatStatutService) {
  }

  // get statuts at launch
  ngOnInit() {
    this.getStatuts();
  }

  // get list of statuts
  public getStatuts(): void{
    this.service.getStatuts().subscribe(posts => this.statuts = posts);
    console.log(this.statuts);
  }

  // insert a new statut
  public insertStatut():void{
    this.inStatut.setLibelle('Test');
    // insert new statut
    this.service.insertStatut(this.inStatut);
    // refresh list of statuts
    this.getStatuts();
    // reset insertion Statut
    this.resetMatStatut(this.inStatut);
  }

  // reset statut
  public resetMatStatut(statut: MatStatut){
    statut.resetData();
  }
}

这是我的服务中的代码:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { MatStatut } from './matStatut';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class MatStatutService {
  constructor(private http: HttpClient) {}

  getStatuts(): Observable<MatStatut[]>{
    return this.http.get<MatStatut[]>('http://localhost/rest/fonctions/matStatut/getAll.php');
  }

  insertStatut(statut: MatStatut) {
    this.http.post('http://localhost/rest/fonctions/matStatut/create.php', {
      mat_statut_libelle: statut.getLibelle()})
      .subscribe(
        res => {
          console.log(res);
        },
        err =>{
          console.log(err);
        });
  }
}

我希望我的解释足够清楚,对我的英语不好感到抱歉。

标签: angulartypescript

解决方案


我认为问题出在 MatStatutService 的 inserStatus 上,您可以为此进行更改:

insertStatut(statut: MatStatut) {
 return this.http.post('http://localhost/rest/fonctions/matStatut/create.php', {
  mat_statut_libelle: statut.getLibelle()});
}

在组件中,您应该具有:

public insertStatut():void{
 this.inStatut.setLibelle('Test');
 // insert new statut
 this.service.insertStatut(this.inStatut).subscribe(res => {
    console.log(res);
    // refresh list of statuts
    this.getStatuts();
    // reset insertion Statut
    this.resetMatStatut(this.inStatut);
 }

这可以确保您首先发生插入,然后您获得更新的列表。

Ps 是 Angular 而不是 Angularjs。


推荐阅读