In AngularFire2, how do I convert incoming json to objects

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



In AngularFire2, how do I convert incoming json to objects



I am using AngularFire2 to read data from Google's Cloud Firestore. The docs show how to receive an updated set of documents on each data change using valueChanges():


valueChanges()


this.items = db.collection<People>('people').valueChanges()



I also have a People class which defines some attributes (first and last name) and a function/method fullName,


People


fullName


export class People
public first: String = '';
public last: String = '';
constructor(...args)
[ this.first, this.last, this.active ] = args;

static MakePersonFrom(input: Any)
return Object.assign(new People(), input);

fullName()
return `Honorable $this.first $this.last`;




The People class matches my documents in the people collection, which each have a first and last name. I want to call fullName on elements of this.items, for example in an html template:


People


people


fullName


this.items


<ul><li *ngFor="person in people | async">person.fullName()</li></ul>



To make this work, I have subscribed to valueChanges and transformed each incoming document:


this.items = db.collection<People>('people').valueChanges()
.pipe(
map(listOfPeople =>
return listOfPeople.map(person =>
return People.makePersonFrom(person);
);
),
tap(item => console.log('Converted', item); ),
);



I am wondering if there is an easier way to do this in AngularFire2. The .pipe code above is mostly boilerplate but for the class name. Is there a variant of valueChanges() that can do this for me?


.pipe


valueChanges()




1 Answer
1



I found that AngularFire2's behavior is consistent with Angular itself, as shown in this small excerpt from the HTTP chapter of the guide:


config: Config;

showConfig() {
this.configService.getConfig()
// clone the data object, using its known Config shape
.subscribe((data: Config) => this.config = ...data );



They use the spread operator instead of Object.assign and are only dealing with one response, but it is otherwise the same.


Object.assign






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard