作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试将应用程序从 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';
@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);
}
}
我知道导入应该更改为:
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
现在您应该使用 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))
)
);
关于angular - 如何在 Angular 6/RxJS 6 中处理 http.get() 的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50180017/
我是一名优秀的程序员,十分优秀!