简体   繁体   中英

I'm getting just key not the value from AngularFire2: Realtime Database version 5 using Angular 6.0

I'm just getting key not the value from AngularFire2. I also tried the Peter Pham Question but the issue remain same.

"@angular/core": "^6.0.0",
"angularfire2": "^5.0.0-rc.11",

Firebase database :

在此输入图像描述

category.service.ts:

import { map } from 'rxjs/operators';
import { AngularFireDatabase } from 'angularfire2/database';
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class CategoryService {

  constructor(private db: AngularFireDatabase) { }

  getCategories(){

    return this.db.list('/categories').snapshotChanges().pipe(map(categories=>{
      return categories.map(a =>{
        const value = a.payload.val();
        const key = a.payload.key;
        return {key, ...value};
      })
    }));
  }
}

product-form.component.ts:

import { CategoryService } from './../../category.service';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-product-form',
  templateUrl: './product-form.component.html',
  styleUrls: ['./product-form.component.css']
})
export class ProductFormComponent implements OnInit {

  categories$;

  constructor(public categoryService: CategoryService) {
    this.categories$ = categoryService.getCategories();
   }



  ngOnInit() {
  }

}

product-form.component.html:

<select ngModel name="category" id="category" class="form-control">
   <option value="">- Select -</option>
   <option *ngFor="let c of categories$ | async" [value]="c.key">
    {{c.value.name}} 
   </option>
 </select>

Where I'm making error? Thanks

As recommended by Und3rTow now it's working. I have tried the following code:

product-form.component.html :

<select ngModel name="category" id="category" class="form-control">
  <option value="">- Select -</option>
  <option *ngFor="let c of categories$ | async" [value]="c.key">{{c.name}}</option>
</select>

product-form.component.ts :

import { CategoryService } from './../../category.service';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-product-form',
  templateUrl: './product-form.component.html',
  styleUrls: ['./product-form.component.css']
})
export class ProductFormComponent implements OnInit {

  categories$;

  constructor(public categoryService: CategoryService) { }

  ngOnInit() {
    this.categories$ = this.categoryService.getCategories();
  }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM