简体   繁体   English

Angular2 - TypeError:this.http.get(...)。toPromise不是函数

[英]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. 我尝试按照angular.io上的教程( 游览英雄 )但是我尝试在一些JSON上做出真正的GET请求而不是教程。

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: user.ts是basicly副本heroe.ts在TOH这样:

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:

 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 EXCEPTION:TypeError:this.http.get(...)。toPromise不是函数

Second one is: 第二个是:

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

Service it self looks fine. 服务它自己看起来很好。 I added my service to app.module.ts in this line: 我在这行app.module.ts我的服务添加到了app.module.ts

providers: [ HTTP_PROVIDERS, UserService ]

and it works if I directly return data with some function like (and comment out calling getUsertHttp function): 如果我直接用一些函数返回数据(并注释掉调用getUsertHttp函数), getUsertHttp工作:

  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';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM