【问题标题】:Angular 6 firebase snapshot returns undefinedAngular 6 firebase 快照返回未定义
【发布时间】:2019-03-03 08:33:36
【问题描述】:

我正在将对象上传到我的数据库,然后尝试检索所有项目。在第二步我得到错误。 :

我的对象类:

export class Data {
  $key: string;
  name: string;
  address: string;
  address2: string;
  pscode: string;
  ccode: string;
  name2: string;
  trucks: Trucks;
  trailers: Trailers;
  email: string;
  phone: string;
  city: string;
  country: string;
}

我的服务上传对象(工作正常):

busines = {} as Data;


createItemAuth() {
   this.afDatabase.list(`users/${this.auth.userId}/company/`).push(this.busines)
}

我的服务 getUpload :

 getItem: Observable<any[]>;
 getUploads() {
    this.getItem = this.afDatabase.list(`users/${this.auth.userId}/company/`).snapshotChanges().pipe(map(items => {
      return items.map(a => {
        const data = a.payload.val();
        const $key = a.payload.key;
        const $ref = a.payload.ref;
        return { $key, ...data, $ref };
      });
    }));
    return this.getItem;
  }

在组件中调用它:

uploads: Observable<Data[]>;
ngOnInit() {
   this.uploads = this.back.getUploads();
   console.log(this.back.getUploads())
}                                                           

HTML:(在浏览器中什么都没有)

<div *ngFor="let info of uploads | async">
  <p>{{info.name}}</p>
</div>

在 ngOnInit() 上的 Console.log :

Observable {_isScalar: false, source: Observable, operator: MapOperator} 运算符:MapOperator {project: ƒ, thisArg: undefined} 来源:可观察 {_isScalar: false, _subscribe: ƒ} _isScalar:假 原型:对象

版本控制:

"rxjs": "^6.1.0",
  "firebase": "^5.4.1",
  "@angular/cli": "6.0.0",
    "typescript": "2.7.2",

【问题讨论】:

  • {{info}} 显示什么?
  • 什么都没有,尝试不使用异步 - 对象中的对象不同
  • 试试 this.back.getUploads().subribe((item: any) =&gt; {}) 一个 observable 必须被订阅。猜猜这是漫长的一天,你需要休息一下;)
  • 现在我在控制台中未定义。
  • 更改地图操作并且成功了!

标签: angular typescript firebase firebase-realtime-database angular6


【解决方案1】:

我不得不更改以下代码:

从此:

  getUploads() {
    this.getItem = this.afDatabase.list(`users/${this.auth.userId}/company/`).snapshotChanges().pipe(map(items => {
      return items.map(a => {
        const data = a.payload.val();
        const $key = a.payload.key;
        const $ref = a.payload.ref;
        return { $key, ...data, $ref };
      });
    }));
    return this.getItem;
  }

至此:

 getUploads() {
    this.getItem = this.afDatabase.list(`users/${this.auth.userId}/company/`).snapshotChanges().map((actions) => {
      return actions.map((a) => {
        const data = a.payload.val();
        const $key = a.payload.key;
        const $ref = a.payload.ref;
        return { $key, ...data, $ref };
      });
    });
    return this.getItem;
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-03
    • 1970-01-01
    • 2018-11-30
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多