0

我是Angular 2中的新成員,而且我很困擾HTTP。Angular 2 Http錯誤

該應用程序運行,但當我嘗試讓我的InMemoryDbService失敗。

的錯誤是:

EXCEPTION: Uncaught (in promise): TypeError: Cannot read property '0' of undefined

,但我並不想獲得 '0' 屬性。

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:當我刪除clientes.service.ts

我的代碼函數來獲取(this.url)錯誤消失.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" 
} 
} 

謝謝!

回答

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';,看看您是否仍然有錯誤。

+0

謝謝!我不明白url API是如何工作的。 –