spankymac
spankymac

Reputation: 866

Returning a string value from a Typescript promise

OK, here should be some simple Typescript code. In my mind anyway...

public showDialog(theNickname: string): string {          
        var req = {
            method: 'POST',
            url: '/Q/GetUserDetails',
            data: { nickname: theNickname }
        }
        this.$http(req).then((response) => {

            var c = "Nickname: " + response.data.Nickname + "<br/>";
            c = c + "Score: " + response.data.Score + "<br/>";
            c = c + "Followers: " + response.data.Followers + "<br/>";              
            return c;               

        });

    }   

Of course, it is not returning the string value as it is being returned as a promise. I don't want to use a timeout function. How can I return the string value? It is being called from an Angular function on the html. If I change

public showDialog(theNickname: string): string { 

to

public showDialog(theNickname: string): any { 

it still doesn't work. I am using this code in a UI.Bootstrap Popover.

Thanks!

Upvotes: 8

Views: 40501

Answers (1)

Daryl
Daryl

Reputation: 18895

Paleo answer is correct, but you could be even awesomer and use Async/Await:

async function showDialog(theNickname: string): Promise<string> {          
        const req = {
            method: 'POST',
            url: '/Q/GetUserDetails',
            data: { nickname: theNickname }
        }
        const response = await this.$http(req);
        return `Nickname: ${response.data.Nickname
            }<br/>Score: ${response.data.Score
            }<br/>Followers: ${response.data.Followers}<br/>`;
}   

async function caller() {
    const message = await showDialog("TEST");
    alert(message);  
}

Check it out here

Upvotes: 6

Related Questions