0

I have the following controller:

[Route("api/[controller]")]
[ApiController]
public class TestController : ControllerBase
{
    [HttpGet]
    public IActionResult Test()
    {
        return Ok(new {
            val1 = "value 1",
            val2and3 = ("value 2", "value 3")
        });
    }
}

I also have the following interface and function in Angular:

export interface TestInterface {
  val1: string;
  val2and3: [string, string];
}

getTest(): Observable<TestInterface> {
  const data$ = this.httpClient
    .get<TestInterface>(this.baseUrl + 'api/Test');

  return data$.pipe(
    tap(data => console.log(JSON.stringify(data)))
  );
}

A problem seems to occur in the getTest() function above when I try to obtain data from the controller. In its tap function, I'm able to log the non-Tuple string's value but not those of the Tuple. console.log outputs what follows: {"val1":"value 1","val2and3":{}}

I call getTest() from another place in Angular, with the following lines of code:

let values: TestInterface | undefined;

this.apiService.getTest().subscribe({
  next: data => values = data
});

console.log('Values:' + values?.val2and3);

Logging values?.val2and3 results in the following output: Values:undefined.

I'm too new to Angular to discover what's going wrong. How do I achieve my objective (which is to define the values variable with all the data sent by the controller)?

  • If you work with Google Chrome, you are able to see with DevTools (F12) under the network tap, how the data comes from the controller. Could you post that informations, also? That makes it easier for us to find the correct interface, for you. – Daniel Michelfelder Jan 18 '23 at 22:07
  • I'm new to DevTools, but in its Network tab, the response code is 200 (ok) and the "Response" sub-tab shows `{"val1":"value 1","val2and3":{}}`, whereas the "Preview" sub-tab shows `{val1: "value 1", val2and3: {}}` on line 1, `val1: "value 1"`on line 2, and `val2and3: {}` on line 3. – HasQuestionsAndAnswers Jan 19 '23 at 07:34
  • Ah, ok. If the backend transmit you nothing to the frontend, it is impossible to get data in it. It seems, that the .net json converter has troubles with tuples. The solution of this link: (https://stackoverflow.com/questions/65854979/c-sharp-mvc-cant-deserialize-a-tuple) .. was, to create a custom class for it. Please change your tuple to a small model. – Daniel Michelfelder Jan 19 '23 at 21:45

0 Answers0