Check out our Angular Book Series.

How to I access URL.createObjectURL() in an Angular App?

I've been working in a project where we accessing the browser's URL object in order to use createObjectURL() to download a file created in the browser.

This is an Angular app, because that is often what I work on. It is often considered a best practice to not access global browser variables, but rather to access global elements through Angular injection.

If you're using a normal JavaScript app, you can access URL using the window object, like this.


But, there is no built in way to inject window into an Angular App.

So, I started looking into using a Document injection to reference the Window object. This is unusual because usually the Document is a child of Window, so I wasn't sure if the reverse relationship would be there.

But, it is. Here's how to do it.

First, inject the Document:

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

This uses slightly more complex syntax than a standard injector, because you specify the @Inject() metadata here and use the DOCUMENT injector token.

Once you have that you can access the window object from the document using defaultView:


And once you have the defaultView or Window object, you can drill down into it to access the URL object:

const myURL = this.document.defaultView.URL.createObjectURL(myObjectToCreateUrlFor));

This worked well for us, giving us access to the global window object / URL functionality, without breaking encapsulation of our Angular service that needed to access these values.

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
Comments are not allowed for this entry.
All Content Copyright 2005, 2006, 2007, 2008, 2009 Jeffry Houser. May not be reused without permission
BlogCFC was created by Raymond Camden. This blog is running version