Reputation: 639
I have this problem. I have an interface called Person
which has a optional key called asked
. I need to pass an array of that interface to a function which return an observable of type Person[]
using RXJS.
interface Person {
name string;
asked?: boolean;
}
const persons: Person[] = [
{name: "Wako"},
{name: "Yako"},
{name: "Dot"},
];
const persons$ = (persons: Person[]): Observable<Person[]> {
return of(persons).pipe(
map((p: Person) => {
p.asked = true;
return p;
})
);
}
But I have this problem:
Type 'Observable<Person>' is not assignable to type 'Observable<Person[]>'.
Type 'Person' is missing the following properties from type 'Person[]': length, pop, push, concat, and 16 more.ts(2322)
What does my function persons$
has to do to return a Observable<Person[]>
.
Upvotes: 1
Views: 320
Reputation: 5748
Observable.of(...args)
will always unwrap the array and turn into Observable<Person>
. If you want an Observable<Person[]>
you need to do something like:
const persons$ = (persons: Person[]): Observable<Person[]> {
return of(persons).pipe(
map((people: Person[]) => people.map(p => ({...p, asked: true})))
);
}
Upvotes: 1
Reputation: 1836
You can do it with another solution:
import { from, Observable } from "rxjs";
import { map, toArray } from "rxjs/operators";
interface Person {
name: string;
asked?: boolean;
}
const persons: Person[] = [
{ name: "Wako" },
{ name: "Yako" },
{ name: "Dot" },
];
const persons$ = (persons: Person[]): Observable<Person[]> => {
return from(persons).pipe(
map((p: Person) => ({ ...p, asked: true })),
toArray(),
);
};
persons$(persons)
.subscribe((x) => console.log(x));
Upvotes: 3