我正在尝试发送一些数据,然后恢复所有数据并显示它们,但是它在将新数据添加到服务器之前初始化了该组件。
所以我在显示器上缺少一个元素。
是否可以延迟初始化,然后再执行发布请求,然后再执行获取请求并显示所有元素?
create-organisme.component.ts:
require
display-organisme.component.ts:
import { Component, OnInit } from '@angular/core';
import { OrganismeService } from '../organisme.service';
import { Organisme } from '../organisme';
import { Router } from '@angular/router';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-create-organisme',
templateUrl: './create-organisme.component.html',
styleUrls: ['./create-organisme.component.css'],
providers: [OrganismeService]
})
export class CreateOrganismeComponent implements OnInit {
organisme: string;
description: string;
form = new FormGroup ({
nom: new FormControl(''),
description: new FormControl(''),
});
constructor(private orgService: OrganismeService, private router: Router) { }
ngOnInit() {
}
create(): void {
const org = new Organisme();
org.organisme = this.form.get('nom').value;
org.description = this.form.get('description').value;
this.orgService.create(org)
.subscribe(
(error) => {
console.log('Erreur: ' + error);
}
);
this.router.navigate(['/display']);
}
}
我可以将router.navigate放入订阅中,以便它等待响应吗?
答案 0 :(得分:3)
您无需延迟ngOnInit()
,只需移动以下行即可:
this.router.navigate(['/display']);
在subscribe()
函数内部:
this.orgService.create(org)
.subscribe(
(result) => this.router.navigate(['/display']),
(error) => {
console.log('Erreur: ' + error);
}
);
答案 1 :(得分:0)
您可以在get请求中对此使用debounce(),这样它将延迟您在debounce计时器中指定的时间,如下所述:
return this.http.get(some_url)
.pipe(
debounce(() => timer(1000)), // 1 second
catchError(this.handleError)
);