Angular Lifecycle Hook - 异步数据未定义OnInit

时间:2018-03-07 14:22:37

标签: angular rxjs google-cloud-firestore lifecycle

我正在尝试访问我从firestore文档加载的对象中的数组,但是无法在ngOnInit中对其进行操作,因为在几秒钟之后它在DOM中呈现之前,它是未定义的。

因此,我无法设置一个新材料MatTableDatasource,该数据填充了我需要访问的数组中的数据,并且在尝试这样做时,CLI返回

  

Observable

类型中不存在属性'items'

查看= invoice.component.ts:

import { Component, OnInit, AfterViewInit, Input } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { MatPaginator, MatTableDataSource, MatSort } from '@angular/material';
import { Observable } from 'rxjs/Observable';

import { AngularFireDatabase } from 'angularfire2/database';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from 'angularfire2/firestore';

import { AuthService } from '../../services/auth.service';
import { InvoiceService } from '../invoice.service';

import { Invoice } from '../invoiceModel';

@Component({
  selector: 'app-view-invoice',
  templateUrl: './view-invoice.component.html',
  styleUrls: ['./view-invoice.component.scss']
})

export class ViewInvoiceComponent implements OnInit, AfterViewInit {

  userId: string;
  invoiceId: string;
  invoice: Observable<Invoice>;
  items: object[];

  itemsData = new MatTableDataSource();

  tableColumns = [
    'description'
  ]

  constructor(private authService: AuthService, private invoiceService: InvoiceService, private db: AngularFirestore, private route: ActivatedRoute) {
    this.userId = this.authService.user.uid;

    this.route.params.subscribe(params => {
        this.invoiceId = params.id;
    })

    this.db.collection('/users').doc(this.userId).collection('/invoices').doc(this.invoiceId).ref.get().then(snapshot => {
        this.invoice = snapshot.data() as Observable<Invoice>;
        this.itemsData = this.invoice.items; <-- Here. "Property items does not exist on 'Observable<Invoice' "...
    })

  }

  ngOnInit() {

  }

  ngAfterViewInit() {

  }

}

1 个答案:

答案 0 :(得分:1)

回答新版本

由于您需要在链中调用多个可观察对象:

  • 您的API调用取决于可观察的参数的结果,
  • 设置数据字段取决于API调用的结果
  • 似乎在
  • 之间存在一些可观察的内容

所以你应该使用flatMap来帮助你链接可观察的电话。

this.route.params
    .map(params => params.id)
    .do(id => { 
        // you can remove this block completely if you don't have other use of this.invoiceId
        this.invoiceId = id; 
    }) 
    .flatMap(invoiceId => Observable.fromPromise(
        this.db.collection('/users').doc(this.userId).collection('/invoices').doc(invoiceId).ref.get())))
    .flatMap(snapshot$ => snapshot$) // not completely sure if needed, try with or without this line
    .flatMap(snapshot => snapshot.data() as Observable<Invoice>)
    .subscribe(
        invoice => { 
            this.itemsData.data = invoice.items; 
            console.log('Loaded items : ');
            console.log(invoice.items);
        }, 
        err => {
            console.log('There was an error :');
            console.log(err);
        }
     );