Currently for development I have this environment config:
export const environment = {
production: false,
envName: 'dev',
apiEndpoint: 'https://url.to.server1/api/'
};
In the module.service.ts services I use apoEndpoint like this:
myServiceMethod1(param: any): Observable<Array<Response>> {
return this.httpClient.get(environment.apiEndpoint + 'rest/service/url/...');
My problem now I have to solve is, there are two servers (server1 with endpoint https://url.to.server1/api/ and server2 with endpoint https://url.to.server2/api/) - exactly ident application but with different URLs.
If a user will login, first I have to show at server1 if this user exists and if not then I have to look up at server2. And if the user is stored in database of server2 than any further request in sevices should be with https://url.to.server2/api/. If user is stored in database of server1 than any further request should be done with https://url.to.server1/api/.
My question now would be how to do this in the best way?
You could define an InjectionToken
and provide it through a factory for all the auth modules.
import {mainServer, fallbackServer} from '@env';
@Injectable('root')
export class AuthService {
private server: string;
auth(credentials): Observable<unknown> {
// resolve the server here
// store the server in this.server
}
}
export const AUTH_API = new InjectionToken<string>('com.my.project');
export const authApiProvider = {
provide: AUTH_API,
useFactory: () => {
const authService = inject(AuthService);
return authService.server;
};
}
Then, you can provide the AUTH_API
using the authApiProvider
on every module. Or you might create an interceptor that injects AUTH_API
and sets it to every request.
I would encourage you to put this logic outside the client behind a proxy server and have all your requests go to the server serving your app. This will increase security and prevent you from handling CORS problems.