Obtain PDF File using Typescript

I am attempting to use an AJAX Post to download a PDF file and return the templateFile Model. However, I am encountering an error where it cannot convert type TemplateFileDto to IhttpActionResult. Should I consider returning something different? Any assistance would be greatly appreciated.

printItems(versionKeys: string[]): JQueryPromise<any> {
        console.log('printItems');
        $.ajax({
            type: "post",
            contentType: "application/json",
            data: JSON.stringify(versionKeys),
            url: this.apiUrls.PrintTemplates,
            success: function (data, status, xhr) {
                var file = new Blob([data], { type:' application/pdf' });
                var fileURL = URL.createObjectURL(file);
                window.open(fileURL);


                console.log('success');

            }
        });

        return;
    }

Controller

[HttpGet, HttpPost]
[ApplicationApiAuthorize("Administrator, ContentManager")]
public IHttpActionResult PrintTemplates([FromBody] List<string> versionKeys)
{

    var templates = versionKeys
            .Select(v => TemplatesDataService.GetTemplate(v))
            .ToList();

    var templateIds = templates.Select(b => b.Id).ToList();

    var templateFile = TemplatesDataService.PrintTemplate(templateIds);

    return templateFile;
}

Model

 public class TemplateFileDto
    {
        public long? Id { get; set; }
        public byte[] Content { get; set; }
        public string FileName { get; set; }
        public string ContentType { get; set; }
    }

Answer №1

The issue at hand is that the return type specified for your PrintTemplates method is IHttpActionResult, but the variable templateFile is of type TemplateFileDto.

Since there is no direct relationship between TemplateFileDto and IHttpActionResult (for example, TemplateFileDto does not implement the IHttpActionResult interface), the compiler cannot automatically convert this variable to the correct type, resulting in an error.

For more detailed information on this specific error, you can refer to the following link: here.

To resolve this issue, a simple solution would be to utilize the Ok method by passing templateFile as a parameter. This will ensure that the content being returned is properly formatted and that the HTTP response code is set to 200.

All you need to do is update your PrintTemplates method from:

return templateFile;

To:

return Ok(templateFile);

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 property xyz is not found in the type 'IntrinsicAttributes & interface abc'

I have an array of objects structured like this: const data = { "Large_Plates": [ { "name": "Cauliower/ Shanghai Fried rice with stir fry vegetables", "id": "1", "price_Veg&quo ...

From SQL to Linq: Exploring the RIGHT JOIN function in LINQ

Can anyone assist me in converting the following SQL query with right join to LINQ? SELECT dbo.FinnTrans.SanadID, dbo.FinnTrans.Date, dbo.FinnAccount.ID AS AccID, dbo.FinnAccount.FullId, dbo.FinnAccount.Name, SUM(dbo.FinnTrans.Debit) AS TotalDebit, SUM( ...

In mvc.net 4, Ajax is only compatible with the httpGet method and not with httpPost

There are two methods, httpGet and httpPost, inside the Login action. Currently, when an ajax call is made, it only works with the httpGet method of Login. I would like it to work with the httpPost method of Login. Thank you in advance for your answer! ...

Having trouble with my ASP.net SQL UPDATE query, it's not functioning as expected

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString); conn.Open(); var session_username = Session["user"]; string sql1 = "UPDATE Users SET email='" + newemail.Text + "' WHERE username ...

Alternative option for clicking using Selenium

I am currently experimenting with Selenium in order to automate interactions with a web service. Interestingly, whenever I attempt to click on elements within the webpage using Selenium, it seems like the webpage is able to detect these automated clicks. ...

"Utilize Typescript for defining the parameter type in this

defineProperties(Element.prototype, { querySelector: { value: querySelectorPatched, writable: true, enumerable: true, configurable: true, }, querySelectorAll: { value(this: HTMLBodyElement): NodeListOf< ...

Guide to setting up .env Variables on a DigitalOcean Ubuntu droplet

After deploying my Node.js app on a DigitalOcean Ubuntu droplet, I encountered the need for variables from my .env file. How can I go about creating these variables within the DigitalOcean droplet? ...

The useEffect hook is failing to resolve a promise

I have received a response from an API that I need to display. Here is a snippet of the sample response (relevant fields only): [ { ...other fields, "latitude": "33.5682166", "longitude": "73 ...

Creating unique random shapes within a larger shape on a canvas, as shown in the image

I have a parent rectangle and would like to add up to 10 or fewer rectangles on the right-hand side corner of the parent rectangle, as shown in the image below: I attempted to write code to achieve this, but the alignment is off-center from the parent rec ...

"Exploring the differences between normalization structures and observable entities in ngrx

I'm currently grappling with the concept of "entity arrays" in my ngrx Store. Let's say I have a collection of PlanDTO retrieved from my api server. Based on the research I've done, it seems necessary to set up a kind of "table" to store th ...

Is there a way to incorporate several select choices using specific HTML?

I am currently trying to dynamically populate a select tag with multiple option tags based on custom HTML content. While I understand how to insert dynamic content with ng-content, my challenge lies in separating the dynamic content and wrapping it in mat ...

Converting JSON Arrays into Typescript Arrays

I am working with a JSON file that contains an array object like this: [ { "VergiNo": "XXXXXXX" }, { "VergiNo": "YYYYYY" }, { "VergiNo": "ZZZZZZ" } ] After importing this JSON file into my Typescript file, import * as companies f ...

Steps for creating a table with a filter similar to the one shown in the image below

https://i.sstatic.net/zR2UU.png I am unsure how to create two sub-blocks within the Business A Chaud column and Potential Business Column. Thank you! I managed to create a table with input, but I'm struggling to replicate the PUSH & CtoC Column for ...

Tips for targeting a specific element with providers in Ionic

By using the specified pattern, I am aiming to achieve a unique toolbar or header for only certain pages. Is there a way to accomplish this without injecting the provider and keeping the page as a standalone? My understanding of Ionic is still developing, ...

Exploring in Angular 2 by using First Name, Last Name, and Email for queries

Details Currently, I am working on implementing a search functionality using pipes. Users should be able to search by email, first name, or last name. At the moment, it only works for searching by email. I am looking to extend this capability so that user ...

Ways to address the error in typescript: "Namespace 'fastify' not found"?

Recently, I made the decision to update all of the packages on my fastify-server template. Upon inspection, my package.json file appears as follows: { "name": "backend-template", "version": "1.0.0", &quo ...

Error Encountered in ASP.NET Compilation (Unable to Execute Methods in CodeBehind File)

Whenever I try to include (OnPageIndexChanging="OnPageIndexChanging" PageSize="10") in my gridview on an asp.net Web Form page, the page crashes. Here is how the grid view looks: <asp:GridView ID="netEventGridView" runat=& ...

Is it possible for Angular templates to be dynamic?

In my component, I have a variable named "myVar" that determines which ng-template should be displayed. Let's consider the following example of a component template: <div *ngIf="myVar; then myVar; else nothing"></div> <ng-template #foo ...

What is the best way to arrange an array in either javascript or typescript based on a specific key, and in the case of identical keys,

Below is an array with objects that need to be sorted: [ { "Books": [], "_id": "5dea9a11a8e1bf301c462ce4", "FileName": "AAAAA", "Order": 99999 }, { "_id": "5dea9864a8e1bf301c462cdb", "Books": [], "FileName": "some1", ...

The step-by-step guide to fixing a Gigwage client eslint error using nestJS

Whenever I utilize the gigwage client for my services, I encounter the following eslint error: TS2742: The inferred type of 'findAll' cannot be named without a reference to '@gigwage/client/node_modules/axios'. This is likely not porta ...