FirebaseObjectObservable返回null值

时间:2017-09-01 16:00:44

标签: angular firebase angularfire2 angular-services

我要从firebase中检索单个对象,它不会返回任何值,而不是我有这条消息“FirebaseObjectObservable {_isScalar:false,$ ref:Reference,source:FirebaseObjectObservable,operator:ObserveOnOperator}”

这就是我编写服务的方式,getDataList()方法完美地工作。应该检索单个对象的get getDataD()是我关注的问题。

import { Injectable } from '@angular/core';
import { AngularFireDatabase, FirebaseListObservable , FirebaseObjectObservable} from 'angularfire2/database';
import { Data } from '../data';
import { AngularFireModule } from 'angularfire2';


@Injectable()
export class Ng2fireServiceService {

  private basePath: string = '/data';
  dataL: FirebaseListObservable<Data[]> = null; //  list of objects
  dataD: FirebaseObjectObservable<Data> = null; //   single object

  constructor(private af: AngularFireModule,
              private db: AngularFireDatabase) { }


  getDataList(query={}): FirebaseListObservable<Data[]> {
  this.dataL = this.db.list(this.basePath, {
    query: query
  });
  return this.dataL
  }
// Return a single observable item
  getDataD(key: string): FirebaseObjectObservable<Data> {
    const dataPath =  `${this.basePath}/${key}`;
    this.dataD = this.db.object(dataPath)
    return this.dataD
  }

}

这就是我在我的组件中调用它的方式

import { Ng2fireServiceService } from '../../services/ng2fire-service.service';
import { Component, OnInit} from '@angular/core';
import { Data } from '../../data';
import { Router, ActivatedRoute, Params } from '@angular/router';



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

  id : string ;
  dataD : any;

  constructor( public authService :AuthService, private SVC : Ng2fireServiceService,private router : Router,
    private route : ActivatedRoute) { }

  ngOnInit() {

    this.id = this.route.snapshot.params['id'];

    this.dataD = this.SVC.getDataD(this.id);

    console.log(this.dataD);
  }

}

你有什么想法如何处理这个

1 个答案:

答案 0 :(得分:1)

因为你没有订阅Observable。试试这个:

  ngOnInit() {

    this.id = this.route.snapshot.params['id'];

    this.SVC.getDataD(this.id).subscribe(val => this.dataD = val);