Home > Net >  How to return an object with its functions from API?
How to return an object with its functions from API?

Time:02-13

Considering following C# class in .NET

public class Person
{
    public string name { get; set; }
    public string surname { get; set; }
    
    public string Fullname()
    {
        return this.name   " "   this.surname;
    }
}

and the endpoint

[HttpGet("getperson/")]
public ActionResult<Person> getPerson()
{
    ...
    return person;
}

In my Angular app, I have the function

getPerson(){
    this.http.get(this.api   "getPerson").subscribe(person => {
        person.fullname() // is it possible to do this if the function is not implemented in the frontend?
    }
}

Could I somehow also pass the function with the object to use it without implementing it in the frontend?

CodePudding user response:

Not possible. You need to write FullName method in the Typescript model.

class Person
{
    name: string;
    surname: string;
    
    constructor(name: string, surname: string){
        this.name = name;
        this.surname = surname;
    }

    fullName(): string {
        return this.name   " "   this.surname; 
    }
}

CodePudding user response:

No, you can not.

Think about it as TypeScript code must be compiled. And if you receive code from outside, that code will be not compiled.

  • Related