Issue
I am trying to post some data to the firebase DB and prompt a success message which redirects the user to the same page, resetting the form in case the post request has been successful.
The component involved are add-review.component.ts
and addReview.service.ts
.
add-review.component.ts
is in the add-review
folder and addReview.service.ts
in the service
folder, these two folders are on the same level, nested under app
.
After the service has successfully posted the data, I have been trying to let the other component know, so that the form could be reset() and re-initiated, without luck.
I can't do an eventEmitter
and an @Output()
because the add-review.component.ts
is served through a <router-outlet>
, so there's no direct parent-child link.
Some code now:
add-review.component.ts:
onSubmitReview() {
const newReview = this.addReviewForm.value;
this.addReviewService.addNewReview(newReview);
}
add-review.service.ts:
addNewReview(newReview: Review) {
this.http.post('https://myApp-6c621.firebaseio.com/reviews.json', newReview).subscribe(reportData => {
console.log(reportData);
}
I would like to:
if the data has been successfully posted, return to the page and reset the form (in the service file I am already redirecting using
this.router.navigate(['/add-review']);
) and it works fine.else, return to the same page and the data is still in the form inputs.
How can I update the add-review.component.ts
from the add-review.service.ts
upon successful post request?
I know there might be an easier way, i.e. perform the post request right on the component, but I am interested in how to communicate this sort of things between same-level router-outlet-nested components.
Solution
You need to subscribe to the Observable in the component add-review.component.ts:
onSubmitReview() {
const newReview = this.addReviewForm.value;
this.addReviewService.addNewReview(newReview).subscribe(
response => {
//reset here using reset() method of forms
}, error => {
console.log(error) //catch error
});
}
In your service:
addNewReview(newReview: Review) {
return this.http.post('https://myApp-6c621.firebaseio.com/reviews.json', newReview);
}
Note: Use the reset() method. Refer this doc: https://angular.io/api/forms/FormControl
Answered By - amshu
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.