Return promise in Angular

I am struggling with my Angular Service as I am trying to return a promise with a Typed Array but keep encountering the following error: src/app/city.service.ts(52,22): error TS2339: Property 'places' does not exist on type 'CityService'. I cannot figure out what mistake I am making.

getPlace(coordinates : Coordinates) {
//    var places : Array<Place> = [];


let promise = new Promise((resolve, reject) => {

  this.http.get('http://localhost:3000/api/place/',  {params: coordinates})
      .toPromise()
      .then(

          res => { // Success
             var places: Array<Place>;

            this.places = res.results.map(item => {
              var place = new Place();
              place.place_id = item.place_id;
              place.name = item.name;
              place.vicinity = item.vicinity;
              place.coordinates = new Coordinates();
              place.coordinates.latitude = item.geometry.location.lat;
              place.coordinates.longitude = item.geometry.location.lng;
              return place;
            });

            resolve(this.places);
          },
          msg => { // Error
            reject(msg);
          }
      );
});
return promise;
}

Answer №1

The comment is accurate, variables declared inside functions that are not part of a service should be called without using the this keyword.

 results = res.places.map ....

Answer №2

Exploring a simpler approach to handling promises

This method provides the same outcome without the need for manually creating a new Promise that resolves when the inner promise does. It reduces code complexity and enhances readability.

retrieveLocationDetails(coordinates : Coordinates) {

    return this.http.get('http://localhost:3000/api/place/',  {params: coordinates})
        .toPromise()
        .then(res => {
            var locations: Location[];

            locations = res.results.map(item => {
              var location = new Location();
              location.place_id = item.place_id;
              location.name = item.name;
              location.vicinity = item.vicinity;
              location.coordinates = new Coordinates();
              location.coordinates.latitude = item.geometry.location.lat;
              location.coordinates.longitude = item.geometry.location.lng;
              return location;
            });

            return locations;
        });

}

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

What could be causing Highlight.js to fail to work following a redirect?

After developing a small application to address a specific issue, I encountered a problem while attempting to apply code highlighting using highlight.js. The issue arises when navigating from site1 to site2 or vice versa - the highlight does not take effec ...

Extending Interfaces Using Keys from an Array in Typescript

When dealing with a scenario where you want a pointfree omit, you can achieve this: type PlainObject<T> = {[key: string]: T} const omit = <K extends string>( name: K ) => <T, U extends PlainObject<T> & { [P in K]: T }>( ...

Having trouble accessing the properties of an undefined variable (reading 'VSCODE_TEXTMATE_DEBUG')

Encountering an error while attempting to use Shiki in Nuxt3. The cause is unknown, even after trying to add the environment variable with no success. Here's a recreation of the error: https://stackblitz.com/edit/github-whzftm?file=pages%2F%5B...slug ...

Select the location for rendering the application within the root HTML using Single-SPA

I am strategizing to utilize the single-SPA framework alongside angular in order to construct a microfrontend architecture for a website. The current setup of the website is based on a legacy monolith structure, but we are aiming to transition it into a mi ...

The Intl.DateTime formatter consistently generates incorrect times even after refreshing the component in a React application

Our component is responsible for receiving information from the backend and rendering it. The properties of the component are defined as: interface CitizenshipProps { citizenship?: Citizenship; name?: string; lastName?: string; onUpdateClic ...

The variance in foundational code between Angular 2 and Angular 4

I'm working with a single code base that I created using ng new my-project-name. How can I determine if the code is Angular 2 or 4? I've searched online but haven't been able to find any answers. ...

Encountered an npm error while attempting to start an Angular project

When attempting to run my project using ng serve -o, a warning message popped up on the screen stating: Your global Angular CLI version (15.2.2) is higher than your local version (15.0.4). The local Angular CLI version will be used. To disable this warnin ...

Testing with Karma in Angular 2 rc.6

I am completely new to the concept of Test-Driven Development (TTD) with Karma and Jasmine. I am currently attempting to run a test on my service that pulls data from my database, but I keep encountering errors that say "ReferenceError: Can't find var ...

Using Typescript to Modify Parent Class Properties in Child Class

Consider this scenario: class Parent { propStr = "Hello"; propNum = 42; constructor(propShared) { console.log(this.propStr); // Hello console.log(this.propNum); // 42 console.log(propShared); // w/e } } class Ch ...

Troubleshooting Angular2 Error: Incompatibility with TypeScript - Unable to Assign String

While working on creating a custom pipe in Angular2 for filtering, I encountered the following build error: Error TS2322: Build: Type '() => string' is not assignable to type 'string' Below is my sample code: import { PipeTransf ...

My current setup includes Node.js version 8.11.2 and Angular CLI version 7.1.2. However, upon running Angular CLI 8.0+, it displays an error stating "You are running version v8.11.2 of Node.js, which is not supported

From the beginning of my project, I encountered a version error which led me to uninstall and delete all Node and CLI files before reinstalling them. However, now when I try to run npm start, I am faced with the following message: The current Node.js vers ...

Express server experiencing issues with generating Swagger documentation

I've been working on an Express API and decided to implement documentation using Swagger and JSDoc. However, the documentation is not working as expected. Here's how I've set it up: docs.ts: import swaggerJSDoc, { Options } from "swagg ...

SystemJS TypeScript Project

I am embarking on a journey to initiate a new TypeScript project. My aim is to keep it simple and lightweight without unnecessary complexities, while ensuring the following: - Utilize npm - Implement TypeScript - Include import statements like: import ...

Tips for implementing validation in Angular2/4 using external JS components

There are various methods for handling Angular 2 validation. One common approach is to utilize HTML5 and template/model binding, or to use forms with designated validators. However, implementing special rules can require a significant amount of coding, an ...

Ways to turn off automatic opening of Google login prompt

I have integrated the abacritt/angularx-social-login package into my project. After injecting SocialAuthService into my constructor, Google signup functionality is automatically displayed on the frontend. Is there a way to prevent this behavior and inste ...

Angular interceptor alters headers and updates request method

My Angular HTTP interceptor is trying to add Authorization headers to a request, but when the code runs, the resulting request does not behave as expected. The method changes from POST to OPTIONS and an error message is generated: Access to XMLHttpRequest ...

Struggling to display data from Firebase Database in dropdown menu using Angular

Despite my extensive search efforts online, including watching YouTube videos and enrolling in Udemy courses, I have not been able to find the solution to my issue. My goal is to take an observable retrieved from Firebase and populate it into a dropdown me ...

Optimal data structure for storage in a Next.js project with TypeScript

What is the appropriate data type for store in export let store: any; other than any? I have used @ts-igore to suppress TypeScript errors on the last line. How can I address the TypeScript error for that as well? I mentioned the boilerplates utilized in ...

The 'path' property is not found on the 'ValidationError' type when using express-validator version 7.0.1

When utilizing express-validator 7.0.1, I encounter an issue trying to access the path field. The error message indicates that "Property 'path' does not exist on type 'ValidationError'.: import express, { Request, Response } from " ...

The function will continuously run in a loop when utilized within an HTML template

Currently, I am attempting to dynamically set the color value of an <input type="color"> using a function within the TypeScript (TS) file of the component. Here is how I have implemented it: HTML <input type="color" [value]=&q ...