如何获取内容基于id?
如果id为1,如何获取内容,例如localhost:5555 / product / 1? 我的路线文件已经设置
我有 json 文件,如
[
{
"id": "0",
"name": "xxxx",
"icon": "https://wikidownload.com/Download/xxxx.png",
"Website":"http.xxx.com"
},
{
"id": "1",
"name": "zzz",
"icon": "zzzz.png",
"Website":"http.zzz.com"
},
{
"id": "2",
"name": "yyy",
"icon": "yyy.png",
"Website":"http.yyy.com"
}
]
在我的组件:
中 ngOnInit() {
this.route.params
.subscribe(
(params : Params) => {
this.id = params.id; //get the id from the route
this.getWhipById(this.id);
}
)
}
getWhipById(id:number){
console.log ( id );
// console.log ( this.productService.getById(id) );
// this.productService.get().map(
// res => {
// return res.filter(item => item.id === id)[0];
// });
}
product.service.ts
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class ProductService {
constructor(private http: Http) {}
/**
* Returns an Observable for the HTTP GET request for the JSON resource.
* @return {string[]} The Observable for the HTTP request.
*/
get(): Observable<string[]> {
return this.http.get('assets/data/products.json')
.map((res: Response) => res.json())
// .do(data => console.log('server data:', data)) // debug
.catch(this.handleError);
}
getById(id: number): Observable<string[]> {
return this.get()
//
// .map((res: Response) => res.find( res => res.id == id));
// .map(movies => movies.find(movie => movie.id == id));
}
/**
* Handle HTTP error
*/
private handleError (error: any) {
// In a real world app, we might use a remote logging infrastructure
// We'd also dig deeper into the error to get a better message
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
}
我在这一点上将id传递给getWhipById()
是我感到困惑的地方
ProductService.get()
将获得所有内容..我使用了地图过滤器,地图查找,但我可以获取内容仅用于我传递的ID。另一件事是调试...如果我做console.log()它只显示可观察和其他属性,但没有关于json内容的任何内容
答案 0 :(得分:0)
只有在订阅时才会运行observable,因此如果它返回.map但没有订阅它,它将永远不会运行.map。尝试订阅地图的结果
getWhipById(id:number){
let mapped = this.productService.get().map(
res => {
return res.filter(item => item.id === id);
});
mapped.subscribe((response) => {
console.log('subscribe' + response.json());
});
}
答案 1 :(得分:0)
需要在调用filter()??
之前调用res.json()this.ProductService
.get()
.map(res => res.json().filter(item => item.id === id))
.subscribe(resp=>console.log(resp));