getItem() 메서드를 사용하여 ID로 배열에서 객체를 검색하려고합니다.각도 4/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 : ngOnInit() : 무효 {
{
"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"
}
]
}
나는 내 구성 요소 내부의 방법을 테스트 그래서
, 어떻게 내 의 getItem 방법으로 관찰 가능한에서 ID로 객체를 검색 할 수 있습니다 죄송합니다 -
은 편집기에서 프로젝트를 만들려고했지만 작동하지 않습니다?
을 당신은 당신의'appModule'에'HttpClientModule'를 가져 아닙니다. docs : https://angular.io/guide/http – Orlandster
HTTP 가져 오기가 정말 충분하다고 생각합니다. HTTP 요청이 getItems() 메소드에서 잘 작동하기 때문입니다. –
HTTP 가져 오기가 실제로 충분하기 때문에 제 http 요청이 getItems() 메소드에서 잘 작동하기 때문에 생각합니다. –