Reputation: 27
I'm trying to send some data and then recover all of them and display them but it initialize the component before the new one is added to the server.
So i'm missing one element on the display.
Is it possible to delay the init and so do the post request and then do the get request and display all the elements?
create-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']);
}
}
display-organisme.component.ts:
import { Component, OnInit } from '@angular/core';
import { Organisme } from '../organisme';
import { OrganismeService } from '../organisme.service';
@Component({
selector: 'app-display-organisme',
templateUrl: './display-organisme.component.html',
styleUrls: ['./display-organisme.component.css'],
providers: [OrganismeService]
})
export class DisplayOrganismeComponent implements OnInit {
organismes: Organisme[];
selectedOrganisme: Organisme;
constructor(private orgService: OrganismeService) { }
onSelect(organisme: Organisme): void {
this.selectedOrganisme = organisme;
}
ngOnInit() {
this.orgService.getOrganismes().subscribe(orgs => this.organismes = orgs);
}
}
Can i put the router.navigate in the subscribe so it waits for the response?
Upvotes: 0
Views: 4127
Reputation: 983
You can use debounce() for this in your get request so that it will be delayed by the time you specify in the debounce timer as mentioned below:
return this.http.get(some_url)
.pipe(
debounce(() => timer(1000)), // 1 second
catchError(this.handleError)
);
Upvotes: 0
Reputation: 24472
You don't need to delay the ngOnInit()
, Just move the following line:
this.router.navigate(['/display']);
Inside your subscribe()
function:
this.orgService.create(org)
.subscribe(
(result) => this.router.navigate(['/display']),
(error) => {
console.log('Erreur: ' + error);
}
);
Upvotes: 3