Reputation: 14108
Goal:
Retrieve the output data
{ age: 4, name: 'Foo' }
{ age: 7, name: 'Bar' }
and then apply the output data in the variable list named "PersonList: Person[] = [];"
Problem:
I tried different solution about how to apply the output data to the variable PersonList but I failed.
Today I don't know how to do it.
Stackblitz:
https://stackblitz.com/edit/ztwnpx?file=index.ts
Thank you!
import { of } from 'rxjs';
import { distinct } from 'rxjs/operators';
interface Person {
age: number,
name: string
}
of<Person>(
{ age: 4, name: 'Foo'},
{ age: 7, name: 'Bar'},
{ age: 5, name: 'Foo'},
).pipe(
distinct((p: Person) => p.name),
)
.subscribe(x => console.log(x));
// displays:
// { age: 4, name: 'Foo' }
// { age: 7, name: 'Bar' }
Upvotes: 0
Views: 35
Reputation: 214295
You can leverage toArray operator:
import { distinct, toArray } from "rxjs/operators";
let persons: Person[];
of<Person>(
{ age: 4, name: "Foo" },
{ age: 7, name: "Bar" },
{ age: 5, name: "Foo" }
)
.pipe(
distinct((p: Person) => p.name),
toArray()
)
.subscribe(x => {
persons = x;
});
console.log(persons);
or you can simply use Observable:
const persons$: Observable<Person[]> = of<Person>(
{ age: 4, name: "Foo" },
{ age: 7, name: "Bar" },
{ age: 5, name: "Foo" }
)
.pipe(
distinct((p: Person) => p.name),
toArray()
);
Upvotes: 1
Reputation: 29355
I'm not sure what you're missing here, but you just need to put the data into an array...
let personList = []; // initialize array
of<Person>(
{ age: 4, name: 'Foo'},
{ age: 7, name: 'Bar'},
{ age: 5, name: 'Foo'},
).pipe(
distinct((p: Person) => p.name),
)
.subscribe(x => personList.push(x)); // add it to the array
Upvotes: 0