【问题标题】:Angular 4 / Can't retrieve data from Array by idAngular 4 / 无法按 id 从数组中检索数据
【发布时间】:2017-10-24 21:38:48
【问题描述】:

我正在尝试使用 getItem() 方法按 id 从 Array 中检索对象。

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(): 无效 {

    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 检索对象?

【问题讨论】:

  • 您没有在您的appModule 中导入HttpClientModule。请参阅文档:angular.io/guide/http
  • Http 导入真的足够了,我想,因为我的 http 请求在 getItems() 方法上运行良好。
  • Http 导入真的足够了,我想,因为我的 http 请求在 getItems() 方法上运行良好。

标签: javascript angular observable angular-services


【解决方案1】:

可能有几个问题:

  getItem(id:number): Observable<IItem> {
    return this.getItems()
    .map(items => items.find(item => item.id === id));
  }
  1. id 参数为NaN
  2. 没有与此id 相关的项目
  3. item.id 不是数字,即 string

只需添加更多日志,就会看到。

【讨论】:

  • getItems() 返回一个对象数组。在控制台中,我可以看到我的对象,其中包含带有 Numbers 值的属性“id”,所以这三个假设似乎都不正确
  • 我严重怀疑,唯一的原因可能是条件 item.id === id 返回 false。
  • 你是对的。在这种情况下,id 是 NaN,我使用 Promises 而不是 Observables 重新编写了代码。
【解决方案2】:

问题来自您的地图功能

试试这个:

getItem(id:number): Observable<IItem> {
    return this.getItems()
    .map((response: Response) => <IItem[]>response.json().itemsData.find(item => item.id === id));
}

【讨论】:

  • 终端抛出错误:无法从用法推断类型参数“T”的类型参数。考虑明确指定类型参数。类型参数候选“IItem []”不是有效的类型参数,因为它不是候选“响应”的超类型。 “响应”类型中缺少属性“包含”。
猜你喜欢
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
  • 2016-06-17
  • 1970-01-01
  • 2017-04-25
  • 2020-06-24
  • 1970-01-01
  • 2019-11-26
相关资源
最近更新 更多