Obtaining a value from within an Angular 'then' block

I have a unique issue that I haven't been able to find a solution for on StackOverflow:

Within an Angular 6 service, I am trying to call a function from another service using TypeScript. Here is the code snippet:

Service1:

myArray: Array<IMyInterface>

...

getArray(): Observable<IMyInterface[]> {

    this.myArray= this.service2.getAnArray(1);
    return Observable.of(this.myArray);
}

Service2

getAnArray(myEntityId): Array<IMyInterface> {
  const myArray2: IMyInterface[] = [];

  this.getConnection().then(connection => {
    connection.invoke('GetEntityById', myEntityId).then((someJson: any) => {
      someJson.forEach( x => myArray2.push(x));       
      return myArray2;
    })
  }); 
}

While executing this, I encounter an error in Service2 stating

A function whose declared type is neither 'void' nor 'any' must return a value.

The issue arises because I need to return the populated array myArray2 only after resolving

connection.invoke('GetEntityById', myId)
, which is why I am attempting to do it within the then block.

How can I overcome this challenge?

Answer №1

This approach may or may not meet your requirements, however, you have the option to simply return the Promise within your service method like so:

fetchArrayByID(entityID) {
  const myArr: IMyInterface[] = [];

  // Make sure to include the return statement
  return this.getConnection().then(connection => {
    return connection.invoke('GetEntityById', entityID).then((jsonResponse: any) => {
      jsonResponse.forEach( item => myArr.push(item));       
      return myArr;
    })
  }); 
}

Your calling code would then be structured as follows:

fetchArrayByID(someIdentifier).then(function(resultArray) {. . .});

Answer №2

Although it's a bit delayed, this information could still be valuable to someone. Utilizing Async/Await can be beneficial in this scenario. Whenever 'await' is encountered, it pauses the thread until the task is completed.

 async retrieveArrayData(entityId) {
    await this.connect();
    try {
      let result = await connection.invoke('GetEntityById', entityId).then((jsonResponse: any) => {
      jsonResponse.forEach(item => myCollection.push(item));
      return myCollection;
      })
   } catch (error) {
  console.log(error);
}

}

To obtain the results (which will be a promise):

this.retrieveArrayData(entityId).then((data) => {
  console.log('Received data:', data);
 
});

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

Incorporate Stripe Elements into your Nuxt Js application

I recently managed to integrate Stripe into my React + Spring Boot application by following the guidelines provided in this documentation: https://stripe.com/docs/stripe-js/react. I used it in my React class component. Now, I am transitioning to Nuxt from ...

Customize the antd theme in a create-react-app project without the need to eject webpack

Struggling with customizing antd in my react app. I'm hesitant to mess with the webpack config.js file since I'm not well-versed in webpack. My goal is to avoid having a site that looks like a generic antd clone, but all my attempts at customizat ...

Accessing the parent div in an Ajax success function

I am looking for a solution to hide a parent div when a link is clicked and an ajax call is successfully made. I have tried placing the hide() function within the success part of the ajax call, but it seems to not work: $('.mylink').click(functi ...

Attaching this to the event listener in React JS

After delving into a beginner's guide on React JS, I encountered a slight hiccup. The issue revolves around a simple problem within the button element; specifically, an event handler that requires passing an argument. This handler serves the purpose o ...

Having trouble getting tsserver-plugins to function properly in either Atom or VSC

My team and I are on a mission to enhance our Angular 2 templates with code completion, similar to what is showcased in this gif. To achieve this goal, we require: tsserver-plugins coupled with tslint-language-service and @angular/language-service We ...

Selenium WebDriver producing unexpected results with getTitle() method

Currently, I am executing an automated test script in a selenium-webdriver environment using Phantomjs. My approach involves running the script through node.js, rather than utilizing Python or C#. The steps I took to set up the environment are outlined b ...

I'm currently attempting to set up the React JS package, but unfortunately encountering some errors in the process

I'm having trouble installing react as I keep receiving errors. My system has npm version 8.12.1 installed. I attempted to downgrade react, but that didn't resolve the issue. I tried the following steps: Update npm using: npm install npm -g Dow ...

"Include the 'unsafe' prefix at the start of the URL in AngularJS

Whenever I attempt to access app://csttree?featuretype=cst_issue&verticalid=2132321&l1=3213&l2=3242 within my app, the URL gets parsed as ==> unsafe:app://csttree?featuretype=cst_issue&verticalid=2132321&l1=3213&l2=3242 Is ...

Resetting the state back to its initial value - which one to use: useState or useReduce?

In order to enhance the functionality of a third-party Authentication service Auth0's useAuth0 hook, I have developed a custom hook called useAuth. This custom hook is responsible for managing local variables that store essential user information like ...

Relocating to reveal or conceal item

I am currently working with jQuery and trying to achieve a specific functionality. My goal is to hide and unhide an element, while also focusing on the exposed area once it becomes visible. I have a link #welcomeselect that, when clicked, should reveal t ...

The overflow hidden function does not seem to be fully functional on the iPad

Struggling to prevent body scrolling when a modal pop-up appears? I've tried setting the body overflow to hidden when opening the modal and resetting it when closing, which worked fine on desktop browsers. However, mobile devices like iPod/iPhone pose ...

Tips for composing content on a sanitized input?

In my small application, I have a feature where a question is displayed with certain words hidden and needs to be filled in by the user. The format of the question looks like this: The {0} {1} {2} his {3} off To achieve this functionality, I wrote the f ...

Commencing a New Ember.js Venture

I've recently started using Ember.js and I'm used to simply typing rails project33 to create a new Rails project. But with Ember, it seems like there are multiple steps involved: mkdir project43 && cd project43 npm install -g genera ...

The Nextjs application folder does not contain the getStaticPaths method

I encountered a problem with the latest nextjs app router when I tried to utilize SSG pages for my stapi blog, but kept receiving this error during the build process app/blog/[slug]/page.tsx Type error: Page "app/blog/[slug]/page.tsx" does not m ...

On the hunt for a specialized JavaScript library for input validation?

Have you ever come across a JavaScript library that allows for variable validation in a convenient chaining style like this one? For example: if(insertLibraryNameHere(myNumberInput).int().min(0).max(10)) This library also has checks for other data types ...

Troubleshooting difficulties integrating NodeJS with R using an R script

I have been attempting to execute an R-script from a js-file but I am consistently receiving a null value as the return. Here is my folder structure: -R_test --example.js --helloWorld.R The contents of example.js are as follows: var R = require(" ...

Linked selection options for state, city, and postal code

I have set up a cascading dropdown list - State -> City -> Pincode . Instead of fetching data from the database, I am using JSON. The dropdown functions smoothly on the local server, but experiences slowness on the web server. Here is a snippet of ...

The NgZone reference error caused the prerendering to fail

I am facing challenges with the implementation of NgZones. Despite defining NgZone, I keep encountering this error: "NodeInvocationException: Prerendering failed because of error: ReferenceError: NgZone is not defined" Below is my app.error-handle.ts file ...

Creating dynamic form fields using AngularJS

I have a form that includes an input field, a checkbox, and two buttons - one for adding a new field and one for deleting a field. I want to remove the add button and instead show the next field when the checkbox is checked. How can I achieve this? angu ...

Load and execute a dynamically created script in JavaScript at the same time

I am exploring the option to load and evaluate a script from a third-party synchronously. Here is an example that currently works well: <head> <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfe ...