2017-07-27 49 views
1

我有一个service.ts,我使用get()方法(http)从本地JSON文件中获取数据。它工作正常。Angular 2+ http get()JSON数据。不能.filter数据

getMusic() { 
    return this.http.get('assets/music.json') 
.map((res:Response) => res.json()) 

在我的课堂我有我的 'suscribe':

ngOnInit() {this.musicService.getMusic().subscribe(
data => { this.music = data.music} 
); 
} 

我的JSON文件看起来是这样的:

{ 
"music" : [ 
    { 
     "no": 11, 
     "name": "Music 1", 
    }, ...... aso.... 

一切都是完美的。那么现在我试图过滤我的数据,所以它只显示no = 11的音乐。

我有这样的进口:

//import 'rxjs/add/operator/map'; 
//import 'rxjs/add/operator/filter'; 
import 'rxjs/Rx'; 

我已经试过几件事情。包括过滤数字而不是字符串,使用==而不是===,将.filter放入内部或外部.map aso。当我尝试这个时,我根本没有收到任何结果。我没有错误,只是没有结果:

getMusic() { 
    return this.http.get('assets/music.json') 
    .map((res:Response) => res.json()) 
    .map(x => x.filter(y => y.name === 'Music 1')); 
} 

回答

1

您有错误filter运算符函数。它应该过滤music

getMusic() { 
    return this.http.get('assets/music.json') 
    .map((res:Response) => res.json()) 
    //filter on `music` object instead of `x` directly 
    .map(x => x.music.filter(y => y.name === 'Music 1')); 
} 
0

filter函数被应用于阵列不是它的一个实例 尝试使用

this.filteredArr = this.music.filter(x=>x.name == 'music 1'); //some condition