-1

I have a typescript page in my Angular application that calls Google maps Timezone.

I don't think it's a good idea, or it doesn't seem like a good idea to store either the url or the key as a hardcoded string. Both of which I'm doing now.

What's the prescribed way to store these two values (url, key)?

  1. In the environment file?

  2. Fetch it from the server every time I want to use it?

  3. Some other file in the Angular project?

Here is the way I construct it. It's all hard coded in the .ts file.

const url = 'https://maps.googleapis.com/maps/api/timezone/json?location=' + this.latitude.value + ',' + this.longitude.value + '&timestamp=' + Math.floor(Date.now() / 1000).toString() + '&key=' + 'my-google-key';
const timeZoneResult = await fetch(url, {
  method: 'GET'
});
const timeZone = await timeZoneResult.json();
R. Richards
  • 24,603
  • 10
  • 64
  • 64
chuckd
  • 13,460
  • 29
  • 152
  • 331

1 Answers1

1

It's more client-side vs server-side. Ideally, in angular applications keys, api_url's are mentioned in environment files (because of different values in different environments, which gets resolved when you generate a prod code). If you somehow wanted to keep keys or URL stuff on the server-side then :

  1. Write a resolver for your initial route,hit your server api get th ekeys and URL and fetch stuff .
  2. APP_INITIALIZER as soon your application loads up check [APP_INITIALIZER]

Following (1) will trouble you whenever you will visist that route, it will trigger resolve, so to keep a check on your script URL whether it is triggering twice, you have to maintain a flag. In these two ways you can hit server API get the, URL and TOKEN and than can add into DOM.

To Authenticat/Authorize user and than to hit API is another extra layer on top of (1)

P.S. Mostly such services are also mapped with domain, so even if you keep KEY at client side (envrionemnt files of angular app ) it won't cause much (in my limited knowledge).

Monis
  • 165
  • 2
  • 12
  • Hi Monis. Thanks for the advice. I moved the key, url to my environment file. I think for now this is the best solution, but I'll look at the link (app initializer) you provided to see if that might help me. Thanks! – chuckd Sep 18 '21 at 17:54