Search code examples
c#asp.netangulartypescripthttp-post

I am having trouble getting data returned from a post request in angular/typscript frontnend and asp.net backend


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?


Solution

  • 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;
    });