Andurit Andurit - 3 months ago 31
TypeScript Question

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

i try to follow tutorial on angular.io (Tour the Heroes)
But instead of tutorial I try to make real GET request on some JSON.

My code looks like:

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);
}


To service I import just few basic things:

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


Where
user.ts
is basicly copy of
heroe.ts
in TOH so:

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


How I call this specific method in service:
First I try multiple things but while debugging i try just console.log it so:

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


When page is loading in console i found multiple errors:
First one is:


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


Second one is:


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


Service it self looks fine. I added my service to
app.module.ts
in this line:

providers: [ HTTP_PROVIDERS, UserService ]


and it works if I directly return data with some function like (and comment out calling
getUsertHttp
function):

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


I try to describe everything which may be important so sorry if question is kind long a bit.
Please guys can you give me hint what i am doing wrong?

Answer

Looks like you are missing import:

import 'rxjs/add/operator/toPromise';