How to Generate a Unique URL in Angular 7 Using Typescript

I'm struggling to display or download a .pdf file in my Angular 7 project due to issues with window.URL.createObjectURL. Here's the code snippet I've written:

this.userService.getFile(report.id).subscribe(
  res => {
    console.log(res)
    const filename = res.headers.get('content-disposition').split(';')[1].split('=')[1].replace(/\"/g, '')
    const blob = new Blob([res.body], { type: res.body.type })
    const url = window.URL.createObjectURL(blob)
    const a: HTMLAnchorElement = document.createElement('a') as HTMLAnchorElement

    a.href = url
    a.download = filename
    window.document.body.appendChild(a)
    a.click()
    window.document.body.removeChild(a)
    URL.revokeObjectURL(url)
  },
  err => {
    console.log(err)
  }

The function getFile() makes a simple HTTP request

getFile(fileId: string): Observable<any> {
   return this.http.get(environment.API_URL + '/file/' + fileId, {observe: 'response', responseType: 'blob'})
}

My IDE is flagging an 'Instance member is not accessible' error with window.URL.createObjectURL()

The file seems to be successfully fetched from the server, and I see the 'Navigate to blob://' message in the console, but the download prompt doesn't appear.

I've used this same method in a previous Angular project (version 6) and it worked perfectly. I'm puzzled why it's not working now. Any advice?

Thank you!

Answer №1

Dealing with a similar issue, I found that removing the mention of window resolved it for me. Here's the snippet of code I used:

export class ExportComponent {
  @Input() data: any;
  @Input() filename = 'exportedData.json';

  exportData() {
    const jsonData = JSON.stringify(this.data);
    const dataBlob = new Blob([jsonData], {type: 'application/json'});
    const downloadLink = document.createElement('a');
    downloadLink.href = URL.createObjectURL(dataBlob);
    downloadLink.download = this.filename;
    downloadLink.click();
  }
}

Answer №2

consider the following when working with Blobs:

1- Ensure your Blob is valid with the code snippet below:

console.log(myBlob instanceof Blob); //true

If not, create your Blob using the Blob constructor.

2- Create a Blob URL without using 'window' by using:

const blobUrl = URL.createObjectURL(myBlob);

3- Safely bypass Angular DomSanitizer (XSS) security by:

const safeblobUrl =  this.sanitizer.bypassSecurityTrustResourceUrl(blobUrl);

Now you can safely use this URL for binding:

<audio [src]="safeblobUrl"></audio>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to trigger a function when a button is enabled in Angular 8?

Here is a portion of my sign-in.component.html file. I have created a function in the corresponding sign-in.component.ts file that I want to trigger when the button below becomes enabled. Here is an example of what I am trying to achieve: <div class= ...

The absence of the @Injectable annotation is causing an issue when importing a JSON

I am currently in the process of integrating a JSON file into my service by using a @inject() tag within the constructor. Below is the code snippet I am working with. DependencyInjectionContainer.ts import { Container, decorate, injectable } from "invers ...

What is the best way to create a function that requires an argument in TypeScript?

I'm looking to bring in a module that requires an argument in Typescript. This is how it looks in javascript: const cors = require('cors')({origin: true}); // JS What would be the equivalent syntax in Typescript? ...

Connect the keys from one enum to either keys or values in another enum

When working with the code below, it is important that the keys of PropertiesNamesInDataBase align with those in User.Keys. While the values of PropertiesNamesInDataBase are used in the backend, it is crucial for uniformity that the names match in the fron ...

Is there a way to retrieve the request URL within the validate function of the http strategy?

Is it possible to access the context object present in guards within the validate method of my bearer strategy, by passing it as an argument along with the token? bearer-auth.guard.ts: @Injectable() export class BearerAuthGuard extends AuthGuard('be ...

Using the index in Vue.js to locate a method within an HTML file

Currently, I am attempting to make use of the reference "index" located within <tr v-for="(note, index) in noteList" v-bind:key="index" in order to call shareToPublic(index). The method selectedID() allows for the selection of the ...

Issue with ToggleButtonGroup causing React MUI Collapse to malfunction

I'm having trouble implementing a MUI ToggleButtonGroup with Collapse in React. Initially, it displays correctly, but when I try to hide it by selecting the hide option, nothing happens. Does anyone have any suggestions on what might be causing this ...

Issues arise with the play method in Storybook and Jest when attempting to use the shouldHaveBeenCalled assertion on a

Here is a snippet of the component code: import { FC, ReactElement, useState, MouseEvent as ReactMouseEvent, ChangeEvent as ReactChangeEvent, } from 'react'; import { Stack, TablePagination } from '@mui/material'; export con ...

Chrome fails the karma tests while phantomjs passes them

I've been struggling with this issue for some time now and can't seem to find a solution. I'm working on an Ionic 2 project that utilizes Angular 2's testing environment. When I run 'ng test' using Karma's Chrome launcher ...

Coordinating Angular to communicate with Node.js to send and receive data

I am currently working on a project using express.js, but I would like to integrate angular into the project to create a single page application. The website currently refreshes the entire content from the server whenever a link is clicked, which seems ine ...

Angular 2 Guide on macOS Sierra Shows "Page Not Found" Error in Web Browser

I've been delving into Angular 2 with TypeScript on my OS X machine. Following the tutorial to the T, I didn't encounter any errors during compilation. Upon executing the npm start command, everything seemed to be smooth sailing as a new tab open ...

Issue with Bootstrap Angular dropdown menu malfunctioning within ChildRoute

Recently, I have been working on integrating admin bootstrap html with Angular. As part of this integration, I added CSS and JS files in angular.json as shown below: "styles": [ "src/styles.css", "src/assets/goo ...

The issue with the meta tag not updating in the view source seems to be related to

I'm facing an issue with updating the meta tag in Angular 6 and Angular Universal. When I make changes, they only reflect in the inspect element and not in the view page source, where it remains the same as the homepage. Homepage.ts . . . import { S ...

Previous states in TypeScript

Just starting out with typescript and trying to work with user files in order to update the state. Currently facing a typescript error that I can't seem to figure out - Error message: Argument of type '(prev: never[]) => any[]' is not as ...

"Access to root is necessary for Angular-cli to run smoothly

After installing angular-cli with the command npm install -g angular-cli, I encountered an error every time I attempted to run any ng command. The error message stated: Error: EACCES: permission denied, open '/home/m041/.config/configstore/ember-cli. ...

Learn how to open a component in a new browser tab using Angular from a different component

I wish to display the MapComponent in a new browser tab when a button in my AppComponent html file is clicked. Currently, when I click the button, the MapComponent opens in a new tab but it also displays the button. How can I configure it so that only the ...

Troubleshooting spacing problems in Angular Material tables

I'm attempting to utilize an Angular Material table in the following way: <div class="flex flex-col pb-4 bg-card rounded-2xl shadow overflow-hidden"> <table mat-table class="" [dataSource]="$candidates ...

Setting up Webpack for my typescript React project using Webpack Version 4.39.2

I have been given the task of fixing the Webpack build in a project that I am currently working on. Despite not being an expert in Webpack, I am facing difficulties trying to make it work. The project has an unconventional react frontend with typescript. I ...

Changes in Angular forms are considered dirty when they differ from their initial state

I am utilizing Angular to design a basic input form like the one shown below. Is there a method available for me to monitor the "true" state of whether a form field has been edited or not, even if a user reverts back to the original value? For example, w ...

Monitor the true/false status of each element within an array and update their styles accordingly when they are considered active

Currently, I am attempting to modify the active style of an element within an array. As illustrated in the image below - once a day is selected, the styles are adjusted to include a border around it. https://i.stack.imgur.com/WpxuZ.png However, my challe ...