angular - 将 firebase 响应映射到类

标签 angular typescript firebase angularfire2

我有以下类(class):

import { Hobbies } from './hobbies';

export class Results {

constructor(
    $key: string,
    first_name: string,
    gender: string,
    intent: string,
    seeking: string,
    training: string,
    latitude: string,
    longitude: string,
    location_desc: string,
    state: string,
    hobbies: Hobbies[],
    cloud_Id: string) {

}

static fromJsonList(array): Results[] {
    return array.map(json => Results.fromJson(json))
}

static fromJson({ $key, cloud_Id, first_name, gender, hobbies, intent, latitude, location_desc, longitude, seeking, state, training }): Results {

    debugger;
    return new Results(
        $key,
        first_name,
        gender,
        intent,
        seeking,
        training,
        latitude,
        longitude,
        location_desc,
        state,
        hobbies,
        cloud_Id);
}


}

我调用 Firebase 并检索与我传入的位置匹配的用户列表,如下所示:

getSearchResults(location: string): Observable<Results[]> {

        return this.af.database.list('/user/', {
            query: {
                orderByChild: 'state',
                equalTo: location
            }
        }).map(Results.fromJsonList);
}

然后我 .map 响应 (Results.fromJsonList);

static 方法 fromJson 中,当我点击 debugger 断点并检查传递的值时,它们都是正确的。

然而,当我在我的组件中记录结果时:

getSearchResultsComponent(gender: string, seeking: string, intent: string, location: string, hobbies?: string) {

  this.searchSubscription = this.searchService.getSearchResults(location).subscribe(results => {
   console.log(results);
  });

}

我看到以下内容:

enter image description here

而我应该看到两个用户的条目,即名字、性别、位置等。

有人可以解释为什么这个映射没有按照我预想的方式工作吗?

最佳答案

使所有Results 类成员public 以便可以通过对象实例访问它们。目前你只是将参数传递给 Results constructor,它们没有分配给任何类成员。

export class Results {

    constructor(
        public $key: string,
        public first_name: string,
        public gender: string,
        public intent: string,
        public seeking: string,
        public training: string,
        public latitude: string,
        public longitude: string,
        public location_desc: string,
        public state: string,
        public hobbies: Hobbies[],
        public cloud_Id: string
    )
    //other code
}

关于angular - 将 firebase 响应映射到类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43228119/

相关文章:

angular - 如何在绑定(bind)到 API 响应的 Angular Material 表中添加分页

angular - 测试方法 setter @Input() Angular 4 Karma

javascript - 以下错误源自您的应用程序代码,而不是 Cypress

java - 如何检查 Firebase-DataBase 中的 key

ios - 如何在一个 block 中从一个 Firebase 查询中获取所有结果

json - 无法使用 Angular 6 和 ASP.NET MVC5 加载本地数据

python - Django 可写嵌套序列化器更新

typescript - 根据条件添加类

javascript - 如何将 Angular 5 Material 选择下拉列表(mat-select)更改为 typescript 代码/文件中的选项之一?

android - Firebase 函数生成 Android 应用