打字稿:嵌套函数的泛型类型

时间:2018-12-05 11:48:32

标签: angular typescript generics nested angular6

我一直在寻找这个问题的答案,但是我无法正确实现它们。也许您可以告诉我正确的方法。

我将解释:我想使用打字稿泛型,而不在我的方法中再使用“任何”。

我正在编写代码以及我想做什么。

在组件中:

this.DatabaseService.getCollection <IUser> ('users', 'lastname'). subscribe (loadData =>
{
    this.listUser = loadData;
});

当我调用getCollection()时,我将调用以下嵌套方法:

  • getCollectionSnapshot()
  • getCollectionRef()

我希望将传递给getCollection()的类型(IUser)转发给已初始化的方法,直到到达getCollectionRef()以获得该类型的返回集合:collection

文件服务:database.service.ts

getCollection <T> (path: string, sortBy ?: string): Observable <T []>
{
    // >>>how do I pass the type (T) to getCollectionSnapshot() ? 

    return this.getCollectionSnapshot (path, sortBy) .pipe (
    map (changes =>
    {
        return changes.map (change =>
        {
            const data = change.payload.doc.data ();
            const id = change.payload.doc.id;
            return {id, ... data};
        });
     }
     ));
}


getCollectionSnapshot (path: string, sortBy ?: string): Observable <any []>
{
    return this.getCollectionRef (path, sortBy) .snapshotChanges ();
}



getCollectionRef (path: string, sortBy ?: string): AngularFirestoreCollection
{
    if (sortBy === undefined)
    {
      return this.afs.collection (path);
    }
    else
    {
      return this.afs.collection (path, ref => ref.orderBy (sortBy));
    }
}

谢谢!我希望填补仿制药方面的空白

1 个答案:

答案 0 :(得分:0)

我不确定我是否理解您的问题。您要将传递给方法 getCollection 的类型参数传递给在 getCollection 中调用的方法。如果是这种情况,这是否适合您:

getCollection <T> (path: string, sortBy ?: string): Observable <T []>
{ 

    return this.getCollectionSnapshot<T> (path, sortBy) .pipe (
    map (changes =>
    {
        return changes.map (change =>
        {
            const data = change.payload.doc.data ();
            const id = change.payload.doc.id;
            return {id, ... data};
        });
     }
     ));
}


getCollectionSnapshot<T> (path: string, sortBy ?: string): Observable <any []>
{
    return this.getCollectionRef<T> (path, sortBy) .snapshotChanges ();
}

getCollectionRef<T> (path: string, sortBy ?: string): AngularFirestoreCollection
{
    if (sortBy === undefined)
    {
         return this.afs.collection (path);
    }
    else
    {
         return this.afs.collection (path, ref => ref.orderBy (sortBy));
    }
} 

注意更改:

getCollectionSnapshot (...

getCollectionRef (...