angular - 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);
});
}
}
我希望我的解释足够清楚,对我的英语不好感到抱歉。
解决方案
我认为问题出在 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。
推荐阅读
- join - 如何加入同一表中存在的列
- python - 为什么我不能从 Python 3.7.2 中的 utils 模块导入 CFEVideoConf 和 image_resize
- hibernate - 无法使用 data.sql 生成 UUID id
- android - 如何在原生应用中处理 JWT 过期机制
- go - 如何在 Go 中使用字符串类型获取字符串的十六进制值
- javascript - 我可以在 javaScript 中使用从 Node.js 抓取的内容吗?
- c++ - 标准中术语相同、相等、等价的含义
- html - HTML表格文本对齐(tbody适应thead)
- javascript - 使用 Math 对象在加载器栏中加载 100%
- android - setOnEditorActionListener 不适用于 Android Pie(9.0)