Getting a string output from a Typescript promise

Here is some Typescript code that I thought would be simple.

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;               

        });

    }   

The issue is that it's not returning the string value because it is being returned as a promise. I am trying to find a solution without using a timeout function. How can I get the string value to return properly? This code is being called from an Angular function within the html.

public showDialog(theNickname: string): any { 

When I change it to this, it still doesn't work. This code is specifically for use in a UI.Bootstrap Popover.

Thank you!

Answer №1

A great suggestion is to utilize Async/Await along with the Paleo solution:

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

async function performAction() {
    const messageToShow = await openDialog("TEST");
    alert(messageToShow);  
}

Explore it further here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leveraging private members in Typescript with Module Augmentation

Recently, I delved into the concept of Module Augmentation in Typescript. My goal was to create a module that could inject a method into an object prototype (specifically a class) from another module upon import. Here is the structure of my folders: . ├ ...

Creating a new component when a click event occurs in React

Currently diving into the world of React while working on a project that involves mapbox-gl. I'm facing an issue where I can successfully log the coordinates and description to the console upon hover, but I can't seem to get the popup to display ...

What steps can I take to troubleshoot and repair my accordion feature within an Angular project?

As a newcomer to Angular, I recently attempted to create an accordion component but encountered unexpected behavior. Here is the HTML code for my attempt: <div class="faq-item-container"> <h1 class="mt-1 mb-5"><strong>Frequently A ...

Accessing embedded component within an Angular template

I have a ng-template that I utilize to generate a modal with a form on top of one of my other components like this: <div> <h1>Main component content...</h1> <button (click)="modals.show(newthingmodal)">Create New T ...

Angular2 RC definitions are not recognized by tsc

Currently, I am utilizing angular version 2.0.0-rc.1, however, I am encountering issues with the typescript compiler (Typescript version 1.8.10). Whenever I run tsc on my project, I am bombarded with numerous errors similar to this one: app/app.componen ...

Apply criteria to an array based on multiple attribute conditions

Given an array containing parent-child relationships and their corresponding expenses, the task is to filter the list based on parents that have a mix of positive and negative expenses across their children. Parents with only positive or negative child exp ...

The option value in mat-autocomplete is not displaying correctly on IOS devices

When I click on the first option in the dropdown menu, it does not display the selected option in the field. However, when I select the second option, then the value of the first option appears, and when I choose the third option, the value of the second o ...

Error: Module not found - Issue with importing SVG files in NextJS

Currently, I am utilizing the babel plugin inline-react-svg to import inline SVGs in NextJS. Here is a snippet from my .babelrc configuration file: { "presets": ["next/babel"], "plugins": [ "inline-react-svg" ...

The ts-node encountered an issue with the file extension in this message: "TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension

When using ts-node, I encountered the following error: $ ts-node index.ts TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /home/projects/node-hddds8/index.ts I attempted to remove "type": "module& ...

What is the best way to connect a ref to a stateless component in React?

I need help creating a stateless component with an input element that can be validated by the parent component. In my code snippet below, I'm facing an issue where the input ref is not being assigned to the parent's private _emailAddress propert ...

Is it possible to create my TypeORM entities in TypeScript even though my application is written in JavaScript?

While I find it easier to write typeorm entities in TypeScript format, my entire application is written in JavaScript. Even though both languages compile the same way, I'm wondering if this mixed approach could potentially lead to any issues. Thank yo ...

Ways to set a default value for a function that returns an unknown type in TypeScript

In my code, I have a customizedHook that returns a value of type typeXYZ || unknown. However, when I try to destructure the returned value, I encounter an error TS2339: Property 'xyz' does not exist on type 'unknown', even though the da ...

AngularJS - Unusual outcomes observed while utilizing $watch on a variable from an external AngularJS service

Within the constructor of my controllers, I execute the following function: constructor(private $scope, private $log : ng.ILogService, private lobbyStorage, private socketService) { this.init(); } private init(){ this.lobbyData = []; this.initial ...

How can a button click function be triggered in another component?

These are the three components in my dashboard.html <top-nav></top-nav> <sidebar-cmp></sidebar-cmp> <section class="main-container" [ngClass]="{sidebarPushRight: isActive}"> <router-outlet></router-outlet> & ...

Ensuring type safety for functions with multiple definitions in TypeScript

The code provided above is prone to failure. TypeScript may mistakenly infer the return type as `string`, allowing you to use the `charAt` method on it even though the actual type is `number`. Is there a solution to enhance the code in a way that TypeScri ...

Tips for merging DTO (Data Transfer Object) with non-DTO objects

I'm currently working on a new endpoint and I need to validate only two parameters (limit and offset) with the dto. The third parameter is not supposed to be checked. My controller test code is not functioning as expected. When I try to use it, the e ...

The module named "mongoose" does not have any member called 'PaginateResult' exported

I'm facing an issue while trying to add the necessary types for "mongoose-paginate" in my Angular 4 project setup with "angular-cli". The problem arises when Webpack throws an error. import {PaginateResult} from "mongoose"; ... getAll(page: number) ...

Simulation service agent partnered with openApi backend

I am currently utilizing MSW along with the OpenAPI-backend package for my project. I aim to mock both the browser server and test server using OpenAPI specifications. With an available OpenAPI definition, I generate `generated.ts` for RTK Query (which is ...

Exploring the money library in typescript after successfully installing it on my local machine

I've been struggling to set up a new library in my TypeScript project for the first time, and I can't seem to get it functioning properly. The library in question is money. I have downloaded it and placed it in the root of my project as instructe ...

What is the correct way to close an ngx-contextmenu in an Angular application?

In my angular project, I implemented an ngx-contextmenu. Within one of my components, the template includes the following code: <div... [contextMenu]="basicMenu"> <context-menu>..... </div> After some time, the component with the conte ...