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!