skip to Main Content

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?

3

Answers


  1. Chosen as BEST ANSWER

    It looks like the post request would not finalize until the function it lived in that started from a button click on the web page finished.

    Instead of creating the guid variable in the same function as the post request, I changed it to a global variable. I am now getting the correct data in the guid variable but only after the button press function finishes.

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

  2. 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;
    });
    
    Login or Signup to reply.
  3. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search