我正在尝试使用方法 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
}
试图在编辑器中创建一个项目,但它不起作用 - 抱歉
那么,如何使用我的 getItem 方法从Observable中通过id检索对象?
答案 0 :(得分:1)
可能有几个问题:
public object this[
DataColumn column
] { get; set; }
getItem(id:number): Observable<IItem> {
return this.getItems()
.map(items => items.find(item => item.id === id));
}
参数为id
NaN
id
不是数字,即item.id
只需添加更多日志即可。
答案 1 :(得分:0)
问题来自你的地图功能
试试这个:
string