gpt4 book ai didi

angular - 如何在 Angular 6/RxJS 6 中处理 http.get() 的结果?

转载 作者:行者123 更新时间:2023-12-02 13:49:02 26 4
gpt4 key购买 nike

我正在尝试将应用程序从 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com