【发布时间】: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
}
试图在编辑器中创建一个项目,但它不起作用 - 抱歉
那么,如何使用 getItem 方法从 Observable 中按 id 检索对象?
【问题讨论】:
-
您没有在您的
appModule中导入HttpClientModule。请参阅文档:angular.io/guide/http -
Http 导入真的足够了,我想,因为我的 http 请求在 getItems() 方法上运行良好。
-
Http 导入真的足够了,我想,因为我的 http 请求在 getItems() 方法上运行良好。
标签: javascript angular observable angular-services