0

I need to load the next script to my angular app

<script src="https://maps.googleapis.com/maps/api/js?key={{google_key}}&libraries=places&language=DE_de"></script>

As I know I can put global js to .angular-cli.json (doesn't work for external scripts) or index.html, but how can I add params (google_key)?

4
  • is your google key changing throughout the lifetime of your app? I think params are good for dynamic content, things that might change often or are unknown before the user renders the frontend. In the case of a google api key, I'd suggest that it might be better to replace such a key during your build process instead of the runtime (for example place it in index.html and replace the key before building the app through a script) Commented Dec 18, 2017 at 10:23
  • @BenediktSchmidt it's not dynamic - right. Do you suggest something like gulp/grunt solution? Commented Dec 18, 2017 at 10:50
  • 1
    are you building through angular-cli? I'm currently doing something similar and I just run a script after angular-cli build that updates my index.html. I'm combining the call in an npm job, it could look something like this ng build && node _yourHtmlUpdateFile_ Commented Dec 18, 2017 at 11:26
  • @BenediktSchmidt thanks, that should works, but I'm still looking for something more beautiful, it's default requirement and angular-cli should support it from the box without hacks Commented Dec 18, 2017 at 11:34

1 Answer 1

1

A quicker solution for a dynamic script in index.html is reference it by id and setting the src attribute from app.component.ts:

googleApi = `https://maps.googleapis.com/maps/api/js?key=
 ${environment.google_key}&libraries=places&language=DE_de`

constructor(@Inject(DOCUMENT) private document: any) {}

ngOnInit() {
  this.document.getElementById('theId').setAttribute('src', this.googleApi) 
}

But, as suggested in the comments, in this case it's probably a better solution to have it as part of the build process.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks, it would work as well, but I think there should be some solution from the box without hacks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.