簡體   English   中英

角度貼圖函數返回“未定義不是函數”

[英]Angular map function is returning “undefined is not a function”

我正在關注本教程https://www.barbarianmeetscoding.com/blog/2016/04/02/getting-started-with-angular-2-step-by-step-6-using-real-data-with- http / ,以及Angular2和VS Code。 我創建了一個db.json服務器來測試api,測試數據看起來像

{
"articles": [{
            "id": 1,
            "name": "Wand of Lightning",
            "description": "A powerful wand of ligthning.",
            "price": 50,
            "imageUrl": "/assets/images/wand.png",
            "specs": [{
                "name": "weight",
                "value": 10
            }, {
                "name": "height",
                "value": 22
            }, {
                "name": "material",
                "value": "wood"
            }],
            "reviews": [{
                "author": "Jaime",
                "title": "I loved it!",
                "content": "I loved the wand of ligthning! I usually use it to charge my laptop batteries!",
                "rating": 5
            }, {
                "author": "John Doe",
                "title": "Underwhelming",
                "content": "I didn't like it at all...",
                "rating": 1
            }]
        }, {
            "id": 2,
            "name": "Staff of Fire",
            "description": "A powerful staff of fire.",
            "price": 150,
            "imageUrl": "/assets/images/staff-of-fire.png",
            "specs": [{
                "name": "weight",
                "value": 10
            }, {
                "name": "height",
                "value": 22
            }, {
                "name": "material",
                "value": "wood and alabaster"
            }],
            "reviews": [{
                "author": "Jaime",
                "title": "I loved it!",
                "content": "I loved the wand of ligthning! I usually use it to charge my laptop batteries!",
                "rating": 5
            }, {
                "author": "John Doe",
                "title": "Underwhelming",
                "content": "I didn't like it at all...",
                "rating": 1
            }]
        }

現在,如果我嘗試使代碼適應示例,我將得到

undefined is not a function

這是items.component.ts

import { Component, OnInit } from '@angular/core';
import {ItemsService} from '../items.service';
import {Item} from '../item';
@Component({
  selector: 'app-items',
  templateUrl: './items.component.html',
  styleUrls: ['./items.component.css']
})
export class ItemsComponent implements OnInit {
 items: Item[] = [];
 errorMessage: string = '';
isLoading: boolean = true;
  constructor(private itemsService: ItemsService) { }

  ngOnInit() {
    this.itemsService
    .getAll().
    subscribe(
      p => this.items =p,
      e => this.errorMessage = e,
      /* onCompleted */ () => this.isLoading = false

    )
  }

}

items.service.ts

import { Injectable } from '@angular/core';

import { Http, Response, RequestOptions, Headers } from '@angular/http';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

import {Item} from './item';
@Injectable()
export class ItemsService {
  private baseUrl: string ='http://localhost:3000';
  constructor(private http: Http) { 

  }
  getAll(): Observable<Item[]>{
    let items = this.http
      .get(`${this.baseUrl}/articles`, { headers: this.getHeaders()})
      .map(this.mapItems)
      .catch(this.handleError);
      return items;
  }
  private getHeaders(){
    let headers = new Headers();
    headers.append('Accept', 'application/json');
    return headers;
  }
  mapItems(response:Response): Item[]{

      return response.json().map(this.toItem)
}

 toItem(r:any): Item{
  let result = <Item>({
    id: r.id,
    name: r.name,
    description: r.description,
    price: r.price,
    imageUrl: r.imageUrl,
  });
  console.log('Parsed item:', result);
  return result;
}





// this could also be a private method of the component class
 handleError (error: any) {
  // log error
  // could be something more sofisticated
  let errorMsg = error.message || `Yikes! There was a problem with our hyperdrive device and we couldn't retrieve your data!`
  console.error(errorMsg);

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









}

注意:制作

return response.json().map(this.toItem)

進入

return response.json()

作品。 但我想使地圖正常工作。

編輯:屏幕截圖

在此處輸入圖片說明

這將解決您的問題-

getAll(): Observable<Item[]> {
    const items = this.http
      .get(`${this.baseUrl}/articles`, {headers: this.getHeaders()})
      .map((response: Response) => this.mapItems(response.json()))
      .catch(this.handleError);
    return items;
  }

mapItems(data: Array<any>): Item[] {
    return data.map(item => this.toItem(item));
  }

我認為您要映射(Array.prototype.map)的是響應對象中的articles ,而不是對象本身。 做這個:

mapItems(response:Response): Item[]{
    return response.json().articles.map(this.toItem)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM