Converting a string or text into a byte array using TypeScript

I am currently working on a task to securely download files (PDF/excel/text) using an API in my Angular 2 (beta) system.

Initially, I utilized a post API with an authentication header and attempted to create a blob from the received data bytes.

The code snippet I used was:

return this.http.get(url, { headers: this.headers}).map( response => response.blob())

However, I encountered an error indicating that the blob method is not implemented in Angular 2 HTTP.

Subsequently, I experimented with the following code where I needed to convert a string to a byte array:

return this.http.get(Configuration.API_URL + url, { headers: this.headers }).map(
            response => {
                var bytes = [];

                var utf8 = encodeURIComponent(response.text());
                for (var i = 0; i < utf8.length; i++) {
                    bytes.push(utf8.charCodeAt(i));
                }    
                var data = new Blob([bytes], { type: 'application/pdf' });
                var fileURL = URL.createObjectURL(data);
                window.open(fileURL);
            }
        );

Unfortunately, I am encountering some issues with the byte array as it does not match the one provided by the API.

I require assistance either in converting a string to a byte array or efficiently utilizing blobs in an Angular 2 HTTP get request.

Answer №1

If you're looking to convert it into ByteArray, consider using this npm package:

https://www.npmjs.com/package/xdata

I hope this solution proves helpful for your needs!

Best regards!

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

The value of the Angular input property within the Bootstrap modal is not defined

I'm currently facing a challenge while incorporating a Bootstrap 4 modal within an Angular 4 application. I am uncertain if nesting a component inside another is causing any issues, but I am unable to determine why an @Input parameter within the modal ...

The Kendo UI grid fails to update after a row is created or modified

My kendo grid isn't refreshing after editing or creating a new row. I have used an AngularJS service for CRUD operations. Here's the controller: app.controller("roadInventoryCtrl", function ($scope, services) { $scope.gridOptions = { ...

Basic image manipulation features integrated with AngularJS

Looking to incorporate some light image layering, scaling, and positioning within a specific box on an AngularJS enabled web page? What is the recommended approach or convention for achieving this functionality? Is using jQuery the best option for impleme ...

The ui-sref hyperlink is not functioning properly on an iPad device

After successfully running my (phonegap) application in Chrome+Ripple and on my android tablet, I encountered a link error when building the app with xCode and testing it on an iPad. $rootScope.$on('$stateChangeError', function(){..}); The foll ...

Challenges with container height in Angular Material Tabs

I'm currently working on an Angular application using Angular Material, and I've encountered a significant issue with the height of my tab content. While I have experience with HTML, CSS, and JavaScript, this is my first venture into Angular deve ...

AngularJS is struggling to retrieve information from an Asp.net webapi 4 endpoint

I'm currently in the process of developing an application using Asp.net Web API and AngularJS. While attempting to retrieve data from the API, I encountered a null error. Asp.net Web API Code [RoutePrefix("api/user")] public class UserController : ...

Retrieving output from a Typescript React Component

Is there a way to retrieve the result from the component class using this method? When I call the ExampleSelectionComponent, it displays the desired output but I also need to access the value of exampleSelectionId in this class. public render() { const ...

Issue with Hostlistener causing incorrect values for nativeelement.value and click events

I have been diving into Angular 4 and working on an autocomplete application. HTML: <form novalidate [formGroup] ="formG"> <input type="text" formGroupName="formCont" id="searText" class="searchBox"> </form> <div class="seracDrop ...

TypeScript enum type encompassing all potential values

One thing I have learned is that keyof typeof <enum> will give us a type containing all the possible keys of an enum. For example, if we have enum Season{ WINTER = 'winter', SPRING = 'spring', SUMMER = 'summer', AUT ...

What strategies can I use to refactor this controller in Angular 1.5 to make it more concise and efficient

I am encountering an issue with a component I have that contains a button. Whenever the button is clicked, it triggers one of two backend services depending on where the component is located. To achieve this, I am currently passing a flag to the component ...

The value of type 'number' cannot be assigned to type 'string | undefined'

Having an issue with the src attribute. I am trying to display an image on my website using the id number from an API, but when I attempt to do so, it gives me an error in the terminal saying 'Type 'number' is not assignable to type 'st ...

Ion2 Ngfor can only be used with arrays as data sources

Struggling to retrieve JSON data using the http client, but facing an error when trying to display it in the view: NgFor only supports binding to Iterables such as Arrays Upon inspecting the console.log output, I noticed that the data is an object contai ...

Learn how to dynamically enable or disable the add and remove buttons in the PrimeNG PickList using Angular 2

I'm currently learning Angular 2 and I'm working on creating a dual list box using PrimeNG's pickList component (https://www.primefaces.org/primeng/#/picklist). Within the pickList, I have table data with 3 columns, along with ADD and REMO ...

Tips on triggering a script when files are altered while serving an Angular application

My current setup involves a node script that converts a markdown file (.md) to HTML and saves it in a directory within an Angular application. This process is invoked by a prebuild step defined in the package.json file. However, after making changes to th ...

Unable to simulate a service and retrieve information in an angular unit test - showing as undefined

In my current project, I have a component that I am trying to write unit tests for. However, when I run the test, I noticed that the value of console.log('**fav**' + favorite[`isFavorite`]); shows up as undefined. This indicates that the data I ...

Prevent link from being clicked again in AngularJS after initial click

I'm in need of some assistance. I am trying to figure out how to disable the link (PAY Now) after it has been clicked on to prevent multiple clicks. <div class="Class1" data-ng-show="ShowButton == 'TRUE'"> <a href="javascript:void( ...

AngularJS is unable to properly show the full calendar on the screen

Currently working with fullcalender.js in conjunction with AngularJS. Encountering an issue where the calendar is not displaying without any error indication, making it difficult to identify the missing component. This marks my initial attempt at combinin ...

What is the process for incorporating a custom type into Next.js's NextApiRequest object?

I have implemented a middleware to verify JWT tokens for API requests in Next.js. The middleware is written in TypeScript, but I encountered a type error. Below is my code snippet: import { verifyJwtToken } from "../utils/verifyJwtToken.js"; imp ...

Occasionally encountering missing modules with Vscode and NestJs

This situation is really frustrating: I started a brand new NestJs project using the @nestjs/cli command. Everything was going smoothly at first. However, after adding a controller with nest generate controller mycontroller and installing types for jasmine ...

Tips for arranging an array of Date.prototype.toLocaleString() in JavaScript

I am dealing with an array of dates that are in the format Date.prototype.toLocaleString('en-GB'). How can I effectively sort these string-based dates? For example, the input looks like this: ["22/07/2020, 8:54:09 AM", "23/07/2020 ...