Using Typescript to set a variable's value from an asynchronous function

Could someone help me with a challenge I am facing while using Typescript? I am attempting to assign the return value from an async service call to a local variable like this:

private searchResult;

public search():void{
             this.DashboardService.dashboardSearch(this.searchParams)
                .then(
                    function (result:ISearchResult) {
                        // promise was fullfilled
                        console.log(result);
                        this.searchResult = result;
                    },
                    function (error) {
                        // handle errors here
                        console.log(error);
                    }
                );
        };
<div id="dashboard-content" ng-controller="dashboardCtrl as vm">
    <h3>{{vm.searchResult}}</h3>
</div>
 

Although the dashboardSearch service is returning an object with data, I seem to be struggling with assigning that data to my local variable.

Below is the error message along with the data displayed in the Google Chrome console.log

https://i.sstatic.net/PNI01.png

I would appreciate guidance on how to successfully bind the data from my service to my local class variable.

Answer №1

protected searchResult;

public initiateSearch():void {
  let self = this;
  
  this.SearchService.searchQuery(this.searchCriteria)
  .then(function(result:ISearchOutcome) {
    // resolving the promise
    console.log(result);
    self.searchResult = result;
  }, function (error) {
    // handling errors
    console.log(error);
  });
};

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

Accessing the parent scope from a directive within a nested ng-repeat in AngularJs

Seeking guidance on accessing the parent scope within a directive nested in an ng-repeat. Here is an example: <div ng-app="myApp" ng-controller="myCtrl"> <div ng-repeat="section in sections"> {{section.Name}} <div ng-rep ...

Can you tell me the appropriate type for handling file input events?

Using Vue, I have a simple file input with a change listener that triggers the function below <script setup lang="ts"> function handleSelectedFiles(event: Event) { const fileInputElement = event.target as HTMLInputElement; if (!fileInp ...

Async Event Handling in ASP.NET is a powerful feature that allows developers

Running ASP.NET 4.0 WEBFORMS presents a challenge for me. After researching various threads on SO and MSDN, I still can't figure out the final piece of this Async puzzle that's been bugging me. The goal is to update a label asynchronously. To te ...

What could be causing the removal of style classes from my element after it is appended?

Could you please explain how it functions? I am attempting to append a div with content using innerHTML and it is working, but without any of the styling classes being applied. const element = document.createElement("div"); element.classList.add("col ...

Problem with escaping special characters in random string HTML

As I was in the process of creating a JavaScript tool to generate random strings, with or without special characters, I stumbled upon an inspiring snippet that caught my attention: (): function randStr(len) { let s = ''; while (len--) s += ...

Pop Ups in PHP: A Guide to Retrieving Variables

I'm a beginner in PHP and I have two files named file_upload.php and test1.php. On file_upload.php, there is a button: <input type="button" value="Link More Opinion" onclick="popUp('test1.php');" /> The JavaScript for that button: & ...

Unable to utilize Next/Link in a NextJs 13 application directory

After enabling the appDir feature in Next.js 13, I encountered an error when adding a Link component: import Link from 'next/link'; function Header() { return ( <div> <Link href="/">Home</Link> </ ...

What is the process for aligning rows with the selected option from the drop-down menu

Alright, so here's the scenario: I have created a table along with two drop-down filters. The first filter is for selecting the Year, and it offers options like "All", "2023", "2022", and "2021". When I pick a specific year, let's say "2022", onl ...

Is it possible to interact with Java SE jars using JavaScript?

I need to integrate an API that is written in Java with a Client written in JavaScript. Is there any way to use this API, possibly along with other Java-SE JARs, in Webstorm? Any assistance would be greatly appreciated. Thank you! ...

Template with a modal overlay

After clicking a button, I want a modal window to appear. However, if the button is inside a template-generated page, the modal window does not appear. <script type="x-template" id="company-template"> <button class="ui but ...

All You Need to Know About Jquery's Selector for Nested Elements

Could someone clarify if the Jquery Statement $(selecterA:not(selectorB), elementA) means "return those elements that match selectorA but not selectorB within elementA"? I am confused by a simple case in Fiddle#1, where both output statements using .length ...

display hidden sections, not entire pages

Similar Question: Printing content of <div id=printarea></div> only? Hello everyone, We are all familiar with the window.print() function. If we have a div containing some content, how can we print it? ...

Encountering a discord bot malfunction while on my Ubuntu server

My discord bot runs smoothly on my Windows 10 setup, but when deployed to the server running Ubuntu Server 20, it encounters a specific error. The issue arises when trying to handle incoming chat messages from the server. While I can read and respond to m ...

tips for exporting database information to an excel file with the help of ajax request and javascript

Recently, I built an application using NDWS with sapui5 _javascript. Within the application, there is a table that contains data synced with the server's database. My goal is to retrieve this data from the table and export it to an Excel document. Her ...

What is the reason behind TypeScript's lack of reporting an incorrect function return type?

It's surprising to see that TypeScript 4.4.3 does not identify an invalid type for the callback function. It makes sense when the function returns a "non-promise" type, but when it returns a Promise, one would expect TypeScript to recognize that we ne ...

Trouble arises when attempting to establish an isolated scope within Angular alongside UI Bootstrap

My table of data is set up with AngularJS, and one of the columns is calculated using a function in the controller. On my webpage, I have a button that opens a modal. When I use UI Bootstrap to open the modal, it creates a new isolated scope (child of the ...

JQuery Client Not Working when accessed from external servers

Encountering something quite unusual with a basic JS GET client. Let's take a look at the code snippet using JQuery: <h3 onclick="$.ajax({ url: 'http://147.102.82.124/', type: 'GET', error: functi ...

How to use Shell command to transfer only HTML files to the designated directory

Currently working on a build script using npm. This build script involves compiling typescript. During the typescript compile process, it copies the folder structure from a ts directory to a dist/js directory. An example of the structure in the ts folde ...

Object.assign changes the original array object in place

I am facing a challenge while attempting to modify the value of a specific index in my state, specifically the property post_comments. The issue lies in the fact that even though I am only modifying a copy of the state, the actual state is also being alter ...

Using jQuery, you can easily insert a <span> tag around selected text and then save this modification permanently in a local HTML file

I have compiled notes in an HTML file stored on my local computer, with the intention of keeping it solely for personal use. For instance, I have a snippet like this: <p> this is an example text</p> My goal is to highlight the word "example" ...