In my application, there is a component known as redirectComponent which is triggered and initialized by other components in the application when they call the route where it's located (http://localhost:4200/redirect/).
Upon being called, redirectComponent makes two API calls to fetch data that is then bound to a form in the template. After the data is successfully loaded, I access the form using ViewChild and submit it using the POST method. Once this is done, the job of the component is complete and a navigation back to the root URL is executed. However, even though the data from the API is resolved, the bound data in the form does not update and is submitted with undefined values.
TYPESCRIPT snippet:
export class RedirectComponent implements AfterViewInit {
userName: string;
sessionToken: string;
sessionDuration: string;
loggedUserNavigationUrl: string = 'someUrl.com';
@ViewChild('microgameform')
microgameForm: ElementRef;
constructor(private thirdPartyGameService: ThirdPartyGameService) { }
async ngAfterViewInit(): Promise<void> {
await this.redirectUserToThirdParty();
}
async redirectToThirdParty(): Promise<void> {
this.sessionDuration = '51';
const gameToken: GameToken = await this.thirdPartyGameService.getGameToken();
this.sessionToken = gameToken.Token;
const nickNameResponse: NickName = await this.thirdPartyGameService.getNickname();
this.userName = nickNameResponse.NickName;
this.microgameForm.nativeElement.submit();
this.router.navigateByUrl('/');
}
}
HTML snippet:
<form #microgameform name="MicrogameForm" [action]="loggedUserNavigationUrl" method="POST" target="_blank">
<input type="hidden" name="Username" [value]="userName"/>
<input type="hidden" name="SessionToken" [value]="sessionToken"/>
<input type="hidden" name="SessionDuration" [value]="sessionDuration"/>
</form>
Upon logging every variable just before
this.microgameForm.nativeElement.submit();
, I discovered that all variables were loaded but not bound to the form, resulting in undefined form values. This was the output I received:
variables and form values before submit
I believe I may have overlooked something in the process. My objective is to retrieve data from the API and then submit it to the form using the post method. It is possible that I am encountering a race-condition issue, but despite experimenting with calling the redirect from different lifecycle hooks like ngAfterViewInit, I continue to encounter various errors...