如何处理Angular 6/RxJS 6中http.get()的结果?
我正在尝试将一个应用程序从Angular 5升级到Angular 6,但在理解如何使用RxJS的新语法时遇到了困难。以下是我尝试迁移的代码:如何处理Angular 6/RxJS 6中http.get()的结果?,angular,rxjs,Angular,Rxjs,我正在尝试将一个应用程序从Angular 5升级到Angular 6,但在理解如何使用RxJS的新语法时遇到了困难。以下是我尝试迁移的代码: import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; @Inje
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
@Injectable()
export class SearchService {
constructor(private http: HttpClient) {}
getAll() {
return this.http.get('assets/data/people.json');
}
search(q: string): Observable<any> {
if (!q || q === '*') {
q = '';
} else {
q = q.toLowerCase();
}
return this.getAll().map((data: any) => {
const results: any = [];
data.map(item => {
// check for item in localStorage
if (localStorage['person' + item.id]) {
item = JSON.parse(localStorage['person' + item.id]);
}
if (JSON.stringify(item).toLowerCase().includes(q)) {
results.push(item);
}
});
return results;
});
}
get(id: number) {
return this.getAll().map((all: any) => {
if (localStorage['person' + id]) {
return JSON.parse(localStorage['person' + id]);
}
return all.find(e => e.id === id);
});
}
save(person: Person) {
localStorage['person' + person.id] = JSON.stringify(person);
}
}
现在应该使用pipe()
而不是map()
,但我在弄清楚如何使用时遇到了问题。如果它像下面这样简单,那就太棒了,但它似乎不是
return this.getAll().pipe(
map(data: any) => {
const results: any = [];
data.map(item => {
// check for item in localStorage
if (localStorage['person' + item.id]) {
item = JSON.parse(localStorage['person' + item.id]);
}
if (JSON.stringify(item).toLowerCase().includes(q)) {
results.push(item);
}
});
return results;
}));
在
map(data:any)=>{}
处缺少一个括号。这应该起作用:
return this.getAll().pipe(
map((data: any) => {
const results: any = [];
data.map(item => {
// check for item in localStorage
if (localStorage['person' + item.id]) {
item = JSON.parse(localStorage['person' + item.id]);
}
if (JSON.stringify(item).toLowerCase().includes(q)) {
results.push(item);
}
});
return results;
}
)
);
您可以通过这样一种更具可读性和功能性的方式进行操作-使用Array.prototype.map函数来实现它的预期用途,并添加一个过滤器:
return this.getAll().pipe(
map(
data => data
.map(item => !!localStorage['person' + item.id]
? JSON.parse(localStorage['person' + item.id])
: item)
.filter(item => JSON.stringify(item).toLowerCase().includes(q))
)
);
这段代码遇到的问题是什么?不应该使用管道而不是地图。您应该将映射(和其他)操作分配给变量,并将变量放入管道中。据我所知,他在这里正确地使用了管道和映射:D对新旧代码进行了15次检查,没有发现新代码有任何错误。错误是什么?另外两件事是错误的,尽管它们不会破坏代码:使用Array.prototype.map不真正将数组映射到新数组,而是将其用作forEach。如果项位于localStorage中,您可能只需首先返回由
过滤的array.map结果即可使代码更干净。我现在看到了,缺少括号:)谢谢funkizer!对于更具功能性的方法,我发现我必须在映射之后进行过滤,以获得与之前相同的功能。没问题。啊,是的,我把它们放错了顺序。最新答案:)
return this.getAll().pipe(
map(
data => data
.map(item => !!localStorage['person' + item.id]
? JSON.parse(localStorage['person' + item.id])
: item)
.filter(item => JSON.stringify(item).toLowerCase().includes(q))
)
);