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

Deleting an element from an array in Mongodb using Angular

My question remains unanswered: Delete an element from an array of an array in MongoDb In the process of creating a basic MEAN application similar to Stack Overflow, I have encountered an issue. Within my application, there are articles with upvotes and d ...

Troubleshooting the issue with the HTTPClient get method error resolution

Currently, I am attempting to capture errors in the HTTP get request within my service file. Below is the code snippet: import { Injectable } from '@angular/core'; import { PortfolioEpicModel, PortfolioUpdateStatus } from '../models/portfol ...

Typescript parameters provide specific data types for functions that can accept either a single argument or two arguments, such as Element.scrollBy

One question I have is how to access the options parameter in the scrollBy() method. Parameters<Element["scrollTo"]> When I use [x: number, y: number] as per the documentation, it does not include options?: ScrollToOptions. scrollTo(option ...

Error messages encountered following the latest update to the subsequent project

Recently, I upgraded a Next project from version 12 to 14, and now I'm encountering numerous import errors when attempting to run the project locally. There are too many errors to list completely, but here are a few examples: Import trace for requeste ...

Kindly include an @Ionic3Annotation for either @Pipe, @Directive, or @Component

During development, this code runs without any issues. However, when attempting to run it in production using the command: Working: ionic cordova run android Not working: ionic cordova run android --prod --release Error Message: [03:34:41] types ...

Angular efficient approach to changing object properties

When working on creating or updating records, I encounter a problem with the length and cleanliness of my code. The dealTypeValues object varies based on the dealDispositionType (buyout or sale), resulting in lengthy and messy code. Does anyone have sugge ...

Unable to retrieve this information within an anonymous function

I am currently working on converting the JSON data received from an API interface into separate arrays containing specific objects. The object type is specified as a variable in the interface. Here is the interface structure: export interface Interface{ ...

Can all intervals set within NGZone be cleared?

Within my Angular2 component, I have a custom 3rd party JQuery plugin that is initialized in the OnInit event. Unfortunately, this 3rd party library uses setIntervals extensively. This poses a problem when navigating away from the view as the intervals rem ...

Unable to translate text on the loading page

Encountering a peculiar issue with the translate service. Here's how I set it up: export class AppComponent implements OnInit { constructor( private translateService: TranslateService, angulartics2GoogleAnalytics: Angulartics2GoogleAnalytics ...

After transitioning from deprecated TSlint to ESLint, which style guide is most similar to TSLint in the ESLint ecosystem?

QUERY - Can anyone recommend the closest ESLint style guide to TSLint for an Angular project in VSCode? I'm looking for a out-of-the-box solution that doesn't require me to tweak too many rules in .eslintrc.json file. I initially set up my style ...

Converting a file buffer to upload to Google Cloud Storage

I have been facing an issue while attempting to upload a file to Google Cloud using a buffer and the save function. The problem I am encountering is that even though the files are uploaded to Google Cloud, they are not in the correct format. When I try to ...

TypeScript's Awaitable concept

Lately, I have been utilizing async / await functions quite frequently in my JavaScript projects. As I make the transition to TypeScript, I am gradually converting some sections of my code bases. In certain scenarios, my functions require a function as an ...

Is there a way to convert a JavaScript object to a class while eliminating unnecessary properties?

In my current project, I am using Typescript with ExpressJS to build APIs. Let's say I have a typescript User model defined as follows: class UserModel { id: number; email: string; password: string; name: string; dob: Date; ge ...

The Angular logout route appears to be neglected

I'm currently working on implementing a LogoutFunction, but I'm running into an issue where it's not being dispatched to my API (Spring Boot). The login functionality works perfectly fine. My goal is to pass an ID to the API and receive a su ...

The file that is currently being downloaded has the .pptx extension, but it is being

Take a look at this code snippet: const generateDownload = ({ link, data, title, settings })=> { const newLink = document.createElement('a'); const blobUrl = link || URL.createObjectURL(new Blob([data], settings)); newLink.setAt ...

The function doc.fromHTML is not recognized in Angular 6

I am having trouble exporting an HTML template to a PDF using the jsPDF library with Angular. I keep getting the error message "doc.fromHTML is not a function." import { Component, ViewChild, ElementRef } from '@angular/core'; import * as jsPDF ...

Exporting the statement from Ionic 3 page.module.ts file

Recently, I started working on Ionic 3 and decided to implement the new page lazy loading approach. Specifically, I have a page named ControlPage that I am focusing on. In most of the resources I referred to, it was recommended to include the following co ...

Problem with Angular 5: Data Binding Issue未知EncodingException

Struggling to understand... I want to make a GET request to my service to retrieve the specific hardware associated with the barcode I scanned - this part is working correctly. The hardware information is returned as an object that looks like this -> ...

The refresh function in the table is not working as expected when implemented in a functional component. The table being used is Material

I am currently utilizing MaterialTable from https://material-table.com/#/docs/features/editable to manage data and perform CRUD operations within my application. I am seeking a way to automatically refresh the table data after any CRUD operation (add, upda ...

What is the best method for eliminating the .vue extension in TypeScript imports within Vue.JS?

I recently created a project using vue-cli3 and decided to incorporate TypeScript for added type safety. Here is a snippet from my src/app.vue file: <template> <div id="app"> <hello-world msg="test"/> </div> </template& ...