2017-03-10 2 views
0

그래서 Angular2를 배우기 시작했고 데이터베이스에있는 데이터를 가져 와서 내 indexpage에 표시하려고 시도하지만 매번 그렇게하려고합니다. "정의되지 않은 속성 '맵'을 읽을 수 없다는 오류가 발생하고 왜 시간을 검색했는지 전혀 알 수 없습니다. 누군가 나를 도울 수 있습니까?Angular2 Map "정의되지 않은 속성 '지도'를 읽을 수 없습니다.

import { Component } from '@angular/core'; 
import { Http, Response, Headers } from '@angular/http'; 
import { Observable } from 'rxjs/Rx'; 
import { Injectable } from '@angular/core'; 
import { Bootcamp } from './Bootcamp'; 

const BOOTCAMP: Bootcamp[] = []; 

@Injectable() 

export class Bootcamptest { 
    private baseUrl: string = 'http://localhost:54220/Bootcampdata'; 

    constructor(private http: Http) { } 

    getAll(): Observable<Bootcamp[]> { 
     let bootcamp$ = this.http 
      .get(`${this.baseUrl}/GetAlleBootcamps`, { headers: this.getHeaders() }) 
      .map(mapBootcamps) 
      .catch(handleError); 

     return bootcamp$; 
    } 

    private getHeaders() { 
     let headers = new Headers(); 
     headers.append('Accept', 'application/json'); 
     return headers; 
    } 
} 

function mapBootcamps(response: Response): Bootcamp[] { 
    // uncomment to simulate error: 
    // throw new Error('ups! Force choke!'); 

    // The response of the API has a results 
    // property with the actual results 

    return response.json().results.map(toBootcamp) 
} 

function toBootcamp(r: any): Bootcamp { 
    let bootcamp = <Bootcamp>({ 
     id: extractId(r), 
     naam: r.name, 
     description: r.description, 
     begindatum: r.begindatum, 
     einddatum: r.einddatum 
    }); 

    console.log('Parsed bootcamp:', bootcamp); 
    return bootcamp; 
} 

// to avoid breaking the rest of our app 
// I extract the id from the person url 
function extractId(bootcampData: any) { 
    let extractedId = bootcampData.url.replace('http://localhost:54220/Bootcampdata/Getallebootcamps', '').replace('/', ''); 
    return parseInt(extractedId); 
} 

function mapBootcamp(response: Response): Bootcamp { 
    // toBootcamp looks just like in the previous example 
    return toBootcamp(response.json()); 
} 

// this could also be a private method of the component class 
function handleError(error: any) { 
    // log error 
    // could be something more sofisticated 
    let errorMsg = error.message || `Error met het laden van data!` 
    console.error(errorMsg); 

    // throw an application level error 
    return Observable.throw(errorMsg); 
} 

구성 요소 클래스는

import { Component, OnInit } from '@angular/core'; 
import { Bootcamp } from './Bootcamp'; 
import { Bootcamptest } from './Bootcamptest'; 

@Component({ 
    selector: 'my-bootcamptest', 
    template: ` 
    <section> 
    <section *ngIf="isLoading && !errorMessage"> 
    Loading our hyperdrives!!! Retrieving data... 
    </section> 
     <ul> 
     <!-- this is the new syntax for ng-repeat --> 
     <li *ngFor="let person of people"> 
      <a> 
      {{bootcamp.naam}} 
      </a> 
     </li> 
     </ul> 
     <section *ngIf="errorMessage"> 
     {{errorMessage}} 
     </section> 
    </section> 
    ` 
}) 
export class Bootcamplistcomponent implements OnInit { 
    bootcamp: Bootcamp[] = []; 
    errorMessage: string = ''; 
    isLoading: boolean = true; 

    constructor(private bootcamptest: Bootcamptest) { } 

    ngOnInit() { 
     this.bootcamptest 
      .getAll() 
      .subscribe(
     /* happy path */ p => this.bootcamp = p, 
     /* error path */ e => this.errorMessage = e, 
     /* onComplete */() => this.isLoading = false); 
    } 
} 
+0

어디에서 오류가 발생합니까? 적어도 파일이나 라인이 생기는 곳에서 제공해야합니다. 'getAll()'메소드가 아닌 것처럼 보입니다. – Supamiu

+0

'mapBootcamps' 함수에서'response.json()'의 내용을 확인하십시오. –

+0

'.get ('$ {this.baseUrl}/GetAlleBootcamps', {headers : this.getHeaders()})')가'null '인 것처럼 보입니다. 문제가되는 'DI'예외는 없습니다. – Brivvirs

답변

0

귀하의 문제는 API에서 오는 것 같다.

mapBootcamps에서 모든 API 응답에 results 속성이 있지만 댓글이 가끔씩 나타나는 것처럼 보입니다.

console.log은 이 object 인 것으로 나타 났으므로 결과가 존재하지 않습니다. null입니다.

response.json().results.map(toBootcamp)response.json()[0].results.map(toBootcamp)으로 변경하면 문제가 발생하지 않지만 데이터를 배열로 처리하거나 API의 반환 형식을 다음과 같이 변경해야합니다. 목적.

+0

내가했을 때 그것은 배열에 1 값이 있다는 것을 보여줬고 그게 문제가 있다고 생각하지 않기 때문에 나는 단지 내 데이터베이스에 더미 데이터의 1 행을 가지고 있기 때문에 정확해야합니다 –

+0

당신이 추가 할 수 있습니다 이'console.log'의 결과? 어쩌면 그것은 객체 일 때처럼 결과 속성을 배열에서 얻으려고하기 때문에 작업이 불가능할 수도 있습니다. – Supamiu

+0

배열 [1] : 개체 Begindatum : "/ 일 (1,448,146,800,000) /" 설명 : "testdata로" Einddatum : "/ 일 (1,450738800000) /" IdBootcamp : 나암 : "Project1의" __proto__ : 객체 길이 : 1,536,__proto__ : 배열 [0] –

4

나는 이것이 오래되었다는 것을 알고 있지만, 나는이 문제를 직접 다루었 다. 난 당신이 또한 다음 자습서를 사용하고 있으리라 믿고있어 : 나는 "mapBootcamps"내 상당을 해부하기 시작 때까지 오랜 시간 동안 갇혀 있었다

https://www.barbarianmeetscoding.com/blog/2016/04/02/getting-started-with-angular-2-step-by-step-6-consuming-real-data-with-http/

. 내가 찾은 것은 "returnres.json(). results.map (toBootcamp)"가 정의되지 않은 값을 반환하고 있습니다. 따라서 ".map (toBootcamp)"메서드가 호출되면 "정의되지 않은 속성 'map'을 읽을 수 없습니다."라는 오류가 발생합니다.

문제를 해결하려면 "return response.json(). results.map (toBootcamp)"줄에서 ".results"를 제거하면됩니다.

희망 하시겠습니까?

관련 문제