Angular2-TypeError:this.http.get(...).toPromise不是一个函数 [英] Angular2 - TypeError: this.http.get(...).toPromise is not a function
问题描述
我尝试遵循有关angular.io的教程(游览英雄) 但是,我没有使用教程,而是尝试在某些JSON上进行真正的GET请求.
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.
我的代码如下:
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';
user.ts
基本上是TOH中heroe.ts
的副本,所以:
Where user.ts
is basicly copy of heroe.ts
in TOH so:
export class User {
id: number;
name: string;
}
我如何在服务中调用此特定方法: 首先,我尝试多种方法,但在调试时,我尝试仅使用console.log记录它:
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:
例外:TypeError:this.http.get(...).toPromise不是函数
EXCEPTION: TypeError: this.http.get(...).toPromise is not a function
第二个是:
例外:TypeError:this.http.get(...).toPromise不是 functionBrowserDomAdapter.logError @
EXCEPTION: TypeError: this.http.get(...).toPromise is not a functionBrowserDomAdapter.logError @
服务本身看起来不错.我在这一行中将服务添加到了app.module.ts
:
Service it self looks fine. I added my service to app.module.ts
in this line:
providers: [ HTTP_PROVIDERS, UserService ]
,如果我直接使用某些函数返回数据(并注释掉调用getUsertHttp
函数),则可以使用它:
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?
推荐答案
好像您缺少导入:
import 'rxjs/add/operator/toPromise';
这篇关于Angular2-TypeError:this.http.get(...).toPromise不是一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!