当前位置: 动力学知识库 > 问答 > 编程问答 >

angularjs - How to run a method when a FirebaseListObservable receives new information in Angular 2

问题描述:

I've connected a Firebase database to an Angular 2 app and have been able to output dynamic data, changing as my Firebase data changes (e.g. if I add more items to they database, they appear on the page).

However, I've been unable to discover any resources that show me how to run a javascript function written in the app.component.ts file, triggered when my firebase data is changed.

I tried using .subscribe(), but I get an error message when the data is updated (it seems that the data returns undefined when the FirebaseObservable is being updated - although I thought subscribe events only happened after data comes in?).

I was wondering if anyone could point me in the right direction of how to scope changes in the FirebaseListObservable data from inside the app.component.ts file.

My goal is to run a function automatically whenever the data changes, but it appears I'm conceptually inept.

App.component.ts

import { Component } from '@angular/core';import { AngularFire, FirebaseListObservable } from 'angularfire2';

@Component({

selector: 'app-root',

templateUrl: 'app.component.html',

styleUrls: ['app.component.css']

})export class AppComponent {

items: FirebaseListObservable<any[]>;

constructor(af: AngularFire) {

this.items = af.database.list('/items', {

query: { orderByChild: 'timestamp' }

});

this.items.subscribe(x => console.log(x[0].sender))

}

}

App.component.html

<ul>

<li class="text" *ngFor="let item of items | async">

{{item.$value}}

</li>

</ul>

Error

zone.js:170 Uncaught TypeError: Cannot read property 'sender' of undefined

enter code here

When I log the outputs of just x, rather than x[0].sender, I noticed this:

[]

[Object]

Which obviously suggests that my subscribe is getting an empty response and then one with content. Is a potential solution some method of telling it to ignore the empty response? Is that possible?

分享给朋友:
您可能感兴趣的文章:
随机阅读: