Angular2 - Issue with calling toPromise() method on this.http.get() function, as it is not recognized

I was following a tutorial on angular.io called Tour the Heroes, but instead of sticking to the tutorial I decided to make a real GET request for some JSON data.

Here is a snippet of my code:

  private userUrl = 'https://jsonplaceholder.typicode.com/users';
  constructor(private http: Http) {}

  getUsersHttp(): Promise<User[]> {
    return this.http.get(this.userUrl)
      .toPromise()
      .then(response => response.json().data as User[])
      .catch(this.handleError);
  }

For the service, I only imported a few basic things:

import { Injectable }     from '@angular/core';
import { Headers, Http, Response } from "@angular/http";
import { User } from './user';

The structure of my user.ts file is essentially a copy of hero.ts in TOH:

export class User {
  id: number;
  name: string;
}

To call this specific method in the service, I initially tried multiple approaches but ended up just logging it for debugging purposes:

 console.log(this.userService.getUsersHttp());

During page load, I encountered several errors in the console: The first one being:

EXCEPTION: TypeError: this.http.get(...).toPromise is not a function

Followed by:

EXCEPTION: TypeError: this.http.get(...).toPromise is not a functionBrowserDomAdapter.logError @

The service itself seems fine. I added my service to app.module.ts like so:

providers: [ HTTP_PROVIDERS, UserService ]

It works if I directly return data with a simple function (and comment out calling the getUsertHttp function):

  getUsers() {
    return [{'id': 1, 'name': 'User1'}, {'id': 2, 'name': 'User2'}];
  }

I've tried to include all relevant information, so apologies for the lengthy question. Could someone please offer guidance on what I might be doing wrong? Thank you in advance!

Answer №1

It appears that an import statement is missing:

import 'rxjs/add/operator/toPromise';

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

Ensuring the proper export of global.d.ts in an npm package

I'm looking to release a typescript npm package with embedded types, and my file structure is set up like so dist/ [...see below] src/ global.d.ts index.ts otherfile.ts test/ examples/ To illustrate, the global.d.ts file contains typings ...

Creating a dynamic routing system for passing data easily

I am interested in sending the filters property from search-products.component.ts to ProductsListComponent using routing. Can this be done? Currently, I can pass static data but how about dynamic data? Below is a snippet of my demo code: app.routing.ts ...

fakeAsync failing to synchronize with async task completion

Scenario In my testing process, I am evaluating a component that utilizes an observable-based service to retrieve and display data for internationalization purposes. The i18n service is custom-made to cater to specific requirements. While the component ...

Steps to deploy an ASP.NET Angular application that has been published

I am working on an Angular application that is being managed by an ASP.NET application following a similar setup as described in this tutorial. During development, I usually use the command dotnet run from within the ASP.NET project directory to build both ...

What is the best way to utilize a React type as props for a custom component?

To make my component work properly, I am required to pass the inputmode as props from an external source. The acceptable values for <input inputMode=<valid values>> are outlined in the React types (node_modules@types\react\index.d.ts) ...

A guide on integrating ngrx-store with a canLoad guard for optimal functionality

Is this a recommended practice? Below is what I am attempting to do: I have two lazy loaded modules: ManagementModule and ConfigurationModule, with the following route configuration: const routes: Routes = [ {path: '', redirectTo: 'manag ...

Issue: Failed to locate module @angular/core

When attempting to run an Angular 4 application, I consistently encounter the following error: ERROR in Could not resolve module @angular/core There are no additional errors present. There are no dependency issues whatsoever as @angular/core is located i ...

Bringing in a TypeScript module to an Angular component

Having trouble with including a specific library in my component Here is the code for my component which uses geolib as the library: import { Component, OnInit } from '@angular/core'; import { StationsService } from '../../../services/stati ...

Creating personalized breakpoints in Material UI using TypeScript

When using the createMuiTheme() function, you have the ability to update breakpoint values like this. const theme = createMuiTheme({ breakpoints: { values: { xs: 0, sm: 600, md: 960, lg: 1280, xl: 1920, }, }, }) ...

Tips for testing an Angular 2 component that integrates a third-party JavaScript library

Seeking guidance on how to properly test the component below that utilizes a 3rd party JavaScript library - import * as Leaflet from "leaflet"; export class GeoFencingComponent { map: any; constructor() { this.map = Leaflet ...

Why the CoreModule in Angular is a must-have for practical development

Though I have gained ample experience in developing Angular-UIs, there is one concept that continues to elude me - the true value of incorporating a CoreModule. To clarify, I understand the purpose of a SharedModule; it houses reusable components (such as ...

Assignment of type 'Object' is incompatible with type in new HttpClient / HttpGetModule implementation within Angular

After following the angular tutorial, I decided to test out the new httpClient.Get method. However, it seems that no matter what, it always returns results of type Object. // HttpClient getHeroes2 () { this.http.get<Hero[]>(this.heroesUrl) ...

What could be the reason for Angular 2 not recognizing this valid regex pattern?

The regular expression shown below is considered valid (check here): ^(\+27|27|0)\s?(\d{2})[-\s]?(\d{3})[-\s]?(\d{4})$ Despite its validity, Angular 2 throws the following error: EXCEPTION: Error in ./App class App - i ...

D3-cloud creates a beautiful mesh of overlapping words

I am encountering an issue while trying to create a keyword cloud using d3 and d3-cloud. The problem I am facing is that the words in the cloud are overlapping, and I cannot figure out the exact reason behind it. I suspect it might be related to the fontSi ...

Enroll in a stream of data while iterating through a loop in an Angular application

I encounter a situation where I must subscribe to an Observable, iterate through the response, and then subscribe to another Observable using data from the initial Observable. getTasks(taskType: Observable<any>): void { taskType // Subscribing ...

Angular 5+ does not have any compatible call signatures for Type Search

Utilizing an addItem function that I found on this site, I encountered the following error message: Error TS2349 (TS) Cannot invoke an expression whose type lacks a call signature. Type 'Search' has no compatible call signatures. Definition o ...

Splitting a string in Typescript based on regex group that identifies digits from the end

Looking to separate a string in a specific format - text = "a bunch of words 22 minutes ago some additional text". Only interested in the portion before the digits, like "a bunch of words". The string may contain 'minute', & ...

An error with code -4058 is preventing the installation of npm packages when running the 'npm install' command after using 'ng new'

Embarking on a new Angular project, I encountered an issue while trying to install packages listed in my package.json file. Despite multiple attempts on both of my computers, the same error persisted, leaving me baffled. Determined not to give up, I seek g ...

Limiting only one checkbox to be selected in a dynamic FormArray in Angular requires some custom logic. This can

I am working on designing an Angular-12 dynamic FormArray: import { Component, OnInit, VERSION } from '@angular/core'; import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms'; @Component({ selecto ...

What is the best way to ensure that a mapped type preserves its data types when accessing a variable?

I am currently working on preserving the types of an object that has string keys and values that can fall into two possible types. Consider this simple example: type Option1 = number type Option2 = string interface Options { readonly [key: string]: Op ...