开发者问题收集

Ionic Angular 未捕获(承诺)错误

2018-03-24
1777

我是 Ionic 的新手。

个 Lynda 课程是我对 Ionic 的入门介绍,我一直在顺利地跟随讲师的教程,直到他介绍了 提供程序 。我的提供程序文件如下:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

/*
  Generated class for the PeopleDataProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class PeopleDataProvider {

  constructor(public http: HttpClient) {
    console.log('Hello PeopleDataProvider Provider');
  }

  getPeople(){
    return this.http.get('https://randomuser.me/api/?results=10&nat=us&seed=d07ade5f51ff3011')
    .map(res => res.json())
    .map(res => res.results);
  }

}

我的 home.ts 文件如下:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

import { DetailPage } from '../detail/detail';
import { PeopleDataProvider } from '../../providers/people-data/people-data';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html',
  providers: [PeopleDataProvider]
})
export class HomePage {

    public people = new Array();
    private detailPage;

  constructor(public navCtrl: NavController, public peopleData:PeopleDataProvider) {

    peopleData.getPeople().subscribe(people => {
      console.log('people',people);
      this.people = people;
    });
    this.detailPage = DetailPage;
  }

  loadDetail(person){
    console.log(person);
    this.navCtrl.push(this.detailPage, {person:person});
  }

}

当应用程序加载时,我收到以下错误:

Typescript Error

Property 'json' does not exist on type 'Object'.

src/providers/people-data/people-data.ts

return this.http.get(' https://randomuser.me/api/?results=10&nat=us&seed=d07ade5f51ff3011 ') .map(res => res.json()) .map(res => res.results);

帖子建议引入 import 'rxjs/add/operator/map'; 作为解决方案。

但是,该导入并不能解决我的问题。

额外的复杂性:

在浏览器刷新几次后,错误变为以下异常,但我无法预测何时发生,也无法控制它何时发生:

ionic Error: Uncaught (in promise): Error: StaticInjectorError(AppModule)[PeopleDataProvider -> HttpClient]:

我不知道这两个错误是否相关。

2个回答

您不必使用 map 并在响应中调用 .json ,仅当您使用旧的 Http 而不是 HttpClient 时才需要这些。

所以你的方法应该是这样的

PeopleDataProvider

import 'rxjs/add/operator/map';
..
getPeople(){
    return this.http.get<any>('https://randomuser.me/api/?results=10&nat=us&seed=d07ade5f51ff3011')
    .map(res => res.results);
}

至于以下错误,

ionic Error: Uncaught (in promise): Error: StaticInjectorError(AppModule)[PeopleDataProvider -> HttpClient]:

确保您已在 AppModule 中导入 HttpClientModule

import {HttpClientModule} from '@angular/common/http'

@NgModule({
  imports:      [ .. , HttpClientModule],
  ..
})

Stackblitz

cyberpirate92
2018-03-24

由于您使用的是 HttpClient,因此显然您使用的是 Angular 4.3+。在此版本之后,.map 和 .json() 已被删除。 尝试这个---

 getPeople(){
return this.http.get('https://randomuser.me/api/?results=10&nat=us&seed=d07ade5f51ff3011');

>

删除--

.map(res => res.json())
.map(res => res.results);
Pranan Subba
2018-03-24