Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/30.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 4通过json循环并获取id上的数据库_Angular - Fatal编程技术网

Angular 4通过json循环并获取id上的数据库

Angular 4通过json循环并获取id上的数据库,angular,Angular,如何根据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",

如何根据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];
    //   });
  }
产品.服务.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);
  }
}
从'@angular/core'导入{Injectable};
从'@angular/Http'导入{Http,Response};
从“rxjs/Observable”导入{Observable};
@可注射()
出口类产品服务{
构造函数(私有http:http){}
/**
*返回JSON资源的HTTP GET请求的可观察值。
*@return{string[]}HTTP请求的可观察对象。
*/
get():可观察{
返回此.http.get('assets/data/products.json')
.map((res:Response)=>res.json())
//.do(data=>console.log('server data:',data))//调试
.接住(这个.把手错误);
}
getById(id:number):可观察{
返回这个。get()
// 
//.map((res:Response)=>res.find(res=>res.id==id));
//.map(movies=>movies.find(movie=>movie.id==id));
}
/**
*处理HTTP错误
*/
私有句柄错误(错误:任意){
//在现实世界的应用程序中,我们可能会使用远程日志记录基础设施
//我们还将深入挖掘错误,以获得更好的信息
让errMsg=(error.message)?error.message:
error.status?`${error.status}-${error.statusText}`:'服务器错误';
console.error(errMsg);//改为登录到控制台
返回可观察抛出(errMsg);
}
}
我将id传递给
getwhipbyd()
,这一点让我感到困惑
ProductService.get()
将获取所有内容。我使用了map filter、map find,但我可以仅针对我传递的id获取内容。另一件事是调试。。。如果我使用console.log(),它只显示observable和其他属性,而不显示json内容的任何内容

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());
        });        
      }
是否需要在调用筛选器()之前调用res.json()


您是否也可以列出服务get方法@marco,或者您是否可以为刚刚添加的服务重新创建一个plunker。。。但是服务工作发现。。。显示所有内容。我需要的是显示一个特定产品的内容。我猜您在映射@marcogomes的可能副本后忘记订阅组件,并用答案更新了它
this.ProductService
  .get()
  .map(res => res.json().filter(item => item.id === id))
  .subscribe(resp=>console.log(resp));