I'm trying to upgrade an application from Angular 5 to Angular 6 and having trouble figuring out how to use RxJS's new syntax. Here's the code I'm trying to migrate:
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);
}
}
I know the imports should change to:
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
And you're supposed to use pipe()
instead of map()
now, but I'm having issues figuring out how. It'd be awesome if it was as simple as the following, but it doesn't seem to be.
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;
}));
You're missing a parentheses at map(data:any) => {}
. This should work:
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;
}
)
);
You could do it in a more readable and functional way like this - use the Array.prototype.map function for what it's supposed to be used and add a filter:
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))
)
);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments