Angular 4 /可以通过id从Array中检索数据

时间:2017-10-24 21:38:49

标签: javascript angular observable angular-services

我正在尝试使用方法 getItem()从ID中检索一个对象。

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

import { IItem } from './item';

@Injectable()
export class ItemsService {
  private _itemsUrl = './items.json';

  constructor(private _http:Http){}

  getItems(): Observable<IItem[]> {
    return this._http.get(this._itemsUrl)
    .map((response: Response) => <IItem[]>response.json().itemsData)
  }

  getItem(id:number): Observable<IItem> {
    return this.getItems()
    .map(items => items.find(item => item.id === id));
  }

}

服务被注入我的组件。

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { ItemsService } from './items.service';
import { IItem } from './item';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  item: IItem;

  constructor(
    private _ItemsService: ItemsService,
    private route: ActivatedRoute
    ) { }

  ngOnInit(): void {

    this._ItemsService.getItems().subscribe(items => console.log(items))

    this.route.params.forEach((params: Params) => {
        let id = +params['id'];
        this._ItemsService.getItem(id).subscribe(item => console.log(item));
    })
   }
}

导出类 IItem

export class IItem {
    id?: number;
    title?: string;
    titleUrl?: string;
}

items.json

{
  "itemsData" : [
    {
      "id": 1,
      "title": "Item 1",
      "titleUrl": "item-1"
    },
    {
      "id": 2,
      "title": "Item 2",
      "titleUrl": "item-2"
    },
    {
      "id": 3,
      "title": "Item 3",
      "titleUrl": "item-3"
    }
  ]
}

我测试组件内的方法:     ngOnInit():void {

    this._ItemsService.getItems().subscribe(items => console.log(items)) //Works fine

    this.route.params.forEach((params: Params) => {
        let id = +params['id'];
        this._ItemsService.getItem(id).subscribe(item => console.log(item)); // Undefined
   }

试图在编辑器中创建一个项目,但它不起作用 - 抱歉

Here!

那么,如何使用我的 getItem 方法从Observable中通过id检索对象?

2 个答案:

答案 0 :(得分:1)

可能有几个问题:

public object this[
    DataColumn column
] { get; set; }
  1. getItem(id:number): Observable<IItem> { return this.getItems() .map(items => items.find(item => item.id === id)); } 参数为id
  2. NaN
  3. 没有项目
  4. id不是数字,即item.id
  5. 只需添加更多日志即可。

答案 1 :(得分:0)

问题来自你的地图功能

试试这个:

string