Home > Back-end >  I am having trouble getting data returned from a post request in angular/typscript frontned and asp.
I am having trouble getting data returned from a post request in angular/typscript frontned and asp.

Time:12-12

I have a web application I am developing that depends on back end processing. I am sending a post request from my Angular(v14)/Typescript front end to an ASP.NET back end.

Back end code

[HttpPost]
public async Task<string> ProcessExcelFile(IFormFile fileData, IFormCollection data)
{
      string guid = await processor.ProcessFile(fileData, data) //Imp not important for question.
    
      return guid;
}

Front end code

var guid: string = "";
this.http.post<string>('/api', formData).subscribe(result => {guid = result;});

I have confirmed the backend is being hit correctly through debugging and returns the correct data.

But the front end "guid" is empty after I call the post request. What I am doing wrong here?

The back end processing could take a few seconds, is that the problem? What can I do about this?

CodePudding user response:

In case it's a JSON response you should be able to do it like this:

// Backend response

{
  "guid": "randomId123",
}
let guid: string;
this.http.post<any>('/api', formData).subscribe(result => {
    guid = result.guid;
});

If it's not JSON Response, could please share how the response look alike?

Update in case the response is just text:

let guid: string;
this.http.post<string>('/api', formData,{ responseType:'text'}).subscribe(result => {
    guid = result;
});

CodePudding user response:

Just by going through the code snippets, not returning an IActionResult stands out to me so you could give this is a shot and check if it solves the issue

[HttpPost]
public async Task<IActionResult> ProcessExcelFile(IFormFile fileData, IFormCollection data)
{
  string guid = await 
  processor.ProcessFile(fileData, data) //Imp not important for question.

  return ok(guid);
}

This basically sends an OK API response with the guid as the content

  • Related