I would like to make a POST request in my angular app as part of the app init logic and I need the some data from the queryParams for the request, but I can't find a way that works in angular 17.
I have tried the following method:
server.ts:
commonEngine
.render({
bootstrap,
documentFilePath: indexHtml,
url: `${protocol}://${headers.host}${originalUrl}`,
publicPath: browserDistFolder,
providers: [
{ provide: APP_BASE_HREF, useValue: baseUrl },
{ provide: 'queryParams', useValue: req.query}
],
})
.then((html) => res.send(html))
.catch((err) => next(err));
});
xy.service.ts
constructor(
@Inject(PLATFORM_ID) private platformId: Object,
@Optional() @Inject('queryParams') public queryParams: any,
private readonly transferState: TransferState
) {
const storeKey = makeStateKey<any>('messageKey');
if(isPlatformBrowser(this.platformId)) {
this.queryParams = this.transferState.get(storeKey, {});
} else {
this.transferState.set(storeKey, this.queryParams);
}
}
It will always return null no matter what. I am aware that it wouldn't work with ng serve
, because it's not using server.ts
, I tried building and running server.mjs
with node. The same thing works with angular 16, but it's not working with angular 17.
Is there are other way to do this in angular 17 or am I just doing something wrong?
You can do something like this,
constructor(private route: ActivatedRoute, @Inject(PLATFORM_ID) private platformId: Object) {
const queryParams = this.route.snapshot.paramMap.get('queryName');
if (isPlatformServer(this.platformId)) {
// Make post request
}
}
basically you can use the activateRoute to get query params and make post request if code running on server. This works, I am using it multiple places.