How to set HttpContext in Angular 18 with decorators?

4 weeks ago 31
ARTICLE AD BOX

I have many methods (GET, POST, PUT..) like this:

profile(): Observable<UserProfileInfoDTO> { return this.http.get<UserProfileInfoDTO>(this.apiUrl + '/user/profile'); }

On the server, it was decided to create the reading and writing modules, which means that hundreds of frontend routes need to add the /r prefix, and the rest the /w prefix, some leave unchanged.

Of cource I can do this:

profile(): Observable<UserProfileInfoDTO> { return this.http.get<UserProfileInfoDTO>(this.apiUrl + '/user/profile', { context: new HttpContext().set(ROUTE_HOST, RouteHost.Read) }); }

But i want to use something like that:

@Read() profile(): Observable<UserProfileInfoDTO> { return this.http.get<UserProfileInfoDTO>(this.apiUrl + '/user/profile'); }

I have interceptor which handles this context and adds the correct prefix. I have tried many options, but none of them work, the context is not set and the interceptor does not see it.

Useful code:

export enum RouteHost { Default, Read, Write } export const ROUTE_PREFIX_BY_HOST: Record<RouteHost, string> = { [RouteHost.Default]: '', [RouteHost.Read]: '/r', [RouteHost.Write]: '/w', }; export const ROUTE_HOST = new HttpContextToken<RouteHost>(() => RouteHost.Default);
Read Entire Article