I have a test project that I am trying to learn Angular. In this project, I have 2 HTML forms that allow me to create a participant. Basically, I divided these forms into 2 subforms for simplicity. I use the first form to capture some demographic data and I use the second form to add more details such as income, educations details etc. My approach was as follows: First create participant, use router
and ActivatedRoute
to navigate the second form by passing the newly created participant id and update.
Basically, the first form is for creating and the second form is for updating purposes only. Those two forms work fine if I place any number as a participant id. However, I am unable to pass the participant id to the second form right after I create the new participant. I get undefined
instead of participant id. I am not sure how I can pass this participant id immedietly right after create one so that I can use the id and update the other details.
Here is the create and update TypeScript codes. Please note that I don't put service and resolver codes in here since they work fine. The only problem is passing the id.
For create (first form):
this.participantService.add(this.participant).subscribe(res => {
console.log('participant has been created!');
});
this.router.navigate(['public-access/form2/' + this.participant.id]);
and update (second form):
export class Form2Component implements OnInit {
participant: any = {};
constructor(
private router: Router,
private route: ActivatedRoute,
private participantService: ParticipantService
) {
route.params.subscribe(p => {
this.participant.id = +p['id'] || 0;
});
}
ngOnInit() {
this.route.data.subscribe(data => {
this.participant = data['participant'];
});
}
submit() {
// participant Update
this.participantService.update(this.participant).subscribe(participant =>{
this.participant = participant;
this.router.navigate(['/public-access/form-success']);
console.log('Participant study status is succefully saved!');
}, error => {
console.log('Participant study status is NOT saved!');
});
}
}
The actual error in the console that I receive is
zone.js:2969 GET http://localhost:5000/api/Participants/undefined 404 (Not Found)
What would be the best way to accomplish this? Any help would be appreciated.
You are calling the navigate
function before you even get an id
from the backend.
What you can probably do is, wait for the response to come from the backend and fetch the id
from there and then navigate.
For create (first form):
this.participantService.add(this.participant).subscribe(res => {
console.log('participant has been created!');
// search for the id in your response object and append that
this.router.navigate(['public-access/form2/' + <id>]);
});