Skip to content Skip to sidebar Skip to footer

Angular How To Display The Result Of A Post Request In A Component

In my Angular application I am trying to display the result of a post request in another component (i.e. confirmation page). I wanted to know what would be the best way for this. I

Solution 1:

For Angular 7.2.0 and higher:

You can make it by using NavigationExtras built into Angular Router. For this you have to add only two things.

First step:

Update this.route.navigate(['/inc/confirmation']) to this

this.router.navigate(['/inc/confirmation'],{state: {response}});

Second step:

In your second component you can access state by adding this to your code

const state = this.router.getCurrentNavigation().extras.state;
this.response = state.response;

Then you can display it.

For Angular 7 and lower:

First step:

Update this.route.navigate(['/inc/confirmation']) to this

this.router.navigate(['/inc/confirmation'],{queryParams: {value: response.result[0].display_value}});

Second step:

In your second component you can access state by adding this to your code

constructor(private route: ActivatedRoute){}
 ...
this.value = this.route.snapshot.queryParamMap.get('value');

Then you can display it.

When you don't want to use URL param:

You can create a service with one property

@Injectable({
  providedIn: 'root'
})
exportclassSharedDataService {
  public sharedData;
  constructor() {
  }
}

Then you can set sharedData before you redirect to another route.

constructor(private sharedService: SharedDataService){}
...
this.sharedService.sharedData = response;
this.route.navigate(['/inc/confirmation']);

You can get that data in your second component.

constructor(private sharedService: SharedDataService){}
...
this.response = this.sharedService.sharedData;

Post a Comment for "Angular How To Display The Result Of A Post Request In A Component"