查询服务方法中的列表并将结果返回给组件?

时间:2018-04-08 18:03:52

标签: javascript angular frontend google-cloud-firestore angularfire2

我遇到的问题是将一组数据从firestore查询返回到需要数据的调用组件。我有一个组件,它注入一个服务类,我想在firestore后端进行所有数据库连接/查询。服务中的方法如下,并且可以完美地检索我想要的记录:

getCardsByUserId(userId: string) {

    return this.afs.firestore.collection('cards').where('uid', '==', userId).get()
        .then((querySnapshot) => {

            if (querySnapshot.size > 0) {
                let cards: Card[];
                querySnapshot.forEach((doc) => {
                    // doc.data() is never undefined for query doc snapshots

                    // THIS DISPLAY EACH ROW CORRECTLY - now how do I pass it back to my component?
                    console.log(doc, " => ", doc.data());

                    // trying to create an object Card put 'push' and return
                    const card = new Card(
                        doc.data().name,
                        doc.data().description,
                        doc.data().imagePath,
                        doc.data().ingredients
                    );
                    cards.push(card);

                });
                //console.log('BEFORE RETUNR', cards);
                return cards;
            } else {
                return [];
            }

        }).catch(err => {
            console.log(err);
        });

}

在我的组件中,我成功注入了服务并在ngOnit中调用了getCardsByUserId()方法(这些卡属性声明为cards: Card[];

ngOnInit() {
    // need to get the cards by user's id

    //console.log(this.authService.getCurrentUser().uid);
    const userId = this.authService.getCurrentUser().uid;
    this.cardService.getCardsByUserId(userId).then(cards => {
        console.log('RESULTS', cards);
        this.cards = cards;
    });
}

但是该组件引发了以下错误:

ERROR in src/app/dashboard/dashboard-section/my-cards/card-list/card-list.component.ts(33,13): error TS2322: Type 'void | Card[]' is not assignable to type 'Card[]'.
  Type 'void' is not assignable to type 'Card[]'.

我尝试过这些方法,但在服务方法的翻译中会丢失一些东西:

return querySnapshot.doc;

====

const cards = [];
querySnapshot.forEach((doc) => {
   cards.push(doc.data());
}
return cards;

理想情况下,我希望getCardsByUserId()返回找到的对象数组...谢谢!

2 个答案:

答案 0 :(得分:2)

如果要获取组件上的数据,可以在 getCurrentUser 函数中返回observable,然后在组件上订阅并根据需要进行读取。

return this.afs.collection('cards', ref => ref.where('uid', '==', userId)).valueChanges();

然后,当你需要阅读observable时,就这样做:

dataList.subscribe(list => {
  console.log(list)
}

我真的建议您阅读官方Angularfire2 docs

答案 1 :(得分:0)

AntonioGarcia感谢你的帮助......这就是我在你指出正确的方向后得到我想要的东西:

在服务方法中:

getCardsByUserId(userId: string) {

        // old realtime firebase way:
        // return this.afs.collection('cards', ref => ref.orderByChild('uid').equalTo(userId)).valueChanges();
        // NEW firestore way:
        return this.afs.collection('cards', ref => ref.where('uid', '==', userId)).snapshotChanges();
}

在我的组件中:

this.subscription = this.cardService.getCardsByUserId(userId)
            .subscribe(cards => {
                this.cards = cards.map(a => {
                    const card: Card = a.payload.doc.data() as Card;
                    card.id = a.payload.doc.id;

                    return card;
                });
            }