【问题标题】:Angular 2 Http ErrorAngular 2 Http 错误
【发布时间】:2018-01-21 01:42:36
【问题描述】:

我是 Angular 2 的新手,我非常依赖 HTTP。

应用程序运行,但是当我尝试获取 InMemoryDbService 时它失败了。

错误是:

异常:未捕获(承诺中):TypeError:无法读取未定义的属性“0”

但我没有尝试访问“0”属性。当我删除 clientes.service.ts 中的函数 get(this.url) 时错误消失

我的代码:

clientes.service.ts

import { Injectable } from '@angular/core';
import { Cliente } from './../models/clientes';
import { Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class ClientesService{

    private headers = new Headers({'Content-Type': 'application/json'});
    private url = '/app/components/apis/clientes-data';// URL a la web api.

    constructor(private http: Http) { }

// Método Get para obtener la lista de objetos.
// 
    get(): Promise<Cliente[]> {
        console.log(this.http.get(this.url)); // THE ERROR IS HERE
        return this.http.get(this.url)        // AND HERE IN 
                   .get(this.url)
                   .toPromise()
                   .then(response => response.json().data as Cliente[])
                   .catch(this.handleError);
    }

    private handleError(error: any): Promise<any> {
        console.error('Ha habido un error con la solicitud '+this.url, error);
        return Promise.reject(error.message || error);
    }

}

clientes-data.service.ts

import { InMemoryDbService } from 'angular2-in-memory-web-api';
export class ClientesData implements InMemoryDbService {
    createDb() {
        let clientes = [
           { id: '1', nombre: 'Pepe' },
           { id: '2', nombre: 'Juan' },
           { id: '3', nombre: 'Paco' },
           { id: '4', nombre: 'Chema' }
        ];
        return {clientes};
     }
}

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { InMemoryWebApiModule } from 'angular2-in-memory-web-api';

// Imports for loading & configuring the in-memory web api
import { XHRBackend } from '@angular/http';

import './rxjs-extensions';
import { AppComponent } from './app.component';
import { routing } from './app.routing';

/** DATAS SERVICE */
import { ClientesData } from './components/apis/clientes-data.service';

/** PIPES */
import { KeyArrayPipe } from './components/pipes/keyArray.pipe';

import { MainComponent } from './main.component';
import { HeaderComponent } from './header.component';
import { FooterComponent } from './footer.component';
import { NavLeftComponent } from './nav-left.component';
import { DashboardComponent } from './components/dashboard.component';
import { ListadoComponent } from './components/listado.component';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    routing,
    HttpModule,
InMemoryWebApiModule.forRoot(ClientesData),
  ],
  declarations: [
    AppComponent, 
    MainComponent, 
    HeaderComponent, 
    FooterComponent, 
    NavLeftComponent,
    DashboardComponent,
    ListadoComponent,
    KeyArrayPipe
  ],
  providers: [
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

package.json

{
 "name": "angular2-tour-of-heroes",
 "version": "0.1.0",
 "scripts": {
   "start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\" ",
   "lite": "lite-server",
   "postinstall": "typings install",
   "tsc": "tsc",
"tsc:w": "tsc -w",
"typings": "typings"
 },
 "dependencies": {
   "@angular/common": "2.0.0-rc.6",
   "@angular/compiler": "2.0.0-rc.6",
   "@angular/compiler-cli": "0.6.0",
   "@angular/core": "2.0.0-rc.6",
   "@angular/forms": "2.0.0-rc.6",
   "@angular/http": "2.0.0-rc.6",
   "@angular/platform-browser": "2.0.0-rc.6",
   "@angular/platform-browser-dynamic": "2.0.0-rc.6",
   "@angular/router": "3.0.0-rc.2",
   "@angular/upgrade": "2.0.0-rc.6",
   "angular2-in-memory-web-api": "0.0.18",
   "concurrently": "^2.2.0",
   "core-js": "^2.4.1",
   "reflect-metadata": "^0.1.3",
   "rxjs": "5.0.0-beta.11",
   "systemjs": "0.19.27",
   "zone.js": "^0.6.17"
 },
 "devDependencies": {
   "concurrently": "^2.2.0",
   "lite-server": "^2.2.2",
   "typescript": "^1.8.10",
   "typings": "^1.3.2"
 }
}

谢谢!!

【问题讨论】:

    标签: angular angular2-services angular2-directives angular2-observables angular2-http


    【解决方案1】:

    您尝试获取数据的方式可能存在一些问题,错误可能是因为您没有指向正确的端点,因此没有数据。

    1. 如果您没有更改该集合的默认 API 基础(查看文档here),则意味着您需要将private url = '/app/components/apis/clientes-data'; 更改为private url = 'app/clientes-data';
    2. 除了第一次更改之外,您还需要非常小心集合名称。现在您正在尝试获取一个不存在的集合。您的集合称为 clientes 而不是 clientesData(这是服务名称)。我建议查看 John Papa 的 example,您可以轻松地看到差异。尝试按照这种方式进行操作。

    请尝试将private url = '/app/components/apis/clientes-data';更改为private url = '/app/clientes';,看看是否还有错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-18
      • 2017-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多