Reputation: 225
I have some records in firebase which I want to display on my HTML page. I have attached the structure of the database. Now, I want to display the years in form an array (which are clickable). On selecting a particular year, I want the respective records to be retrieved in my code.
I tried retrieving the years,but was unable to display them on the page. I tried a static array as years=["1999","1994"] which worked. Only the data from database is not being retrieved and displayed.
<div class="list-group " *ngFor="let year of years">
<a routerLink="records" routerLinkActive="active" >
<mdb-icon fas icon="table" class="mr-3"></mdb-icon>{{year}}</a>
</div>
export class NavigationComponent implements OnInit {
@ViewChild('sidenav', {static: true}) sidenav: ElementRef;
//years = ['1999', '2004', '2019'];
clicked: boolean;
resizedImage: Blob;
years:AngularFireList<any[]>;
// TODO: Need to fix the click effect of years
constructor(af:AngularFireDatabase,
private router: Router,
//private userService: UserService
//private ng2ImgMax: Ng2ImgMaxService
) {
this.clicked = this.clicked === undefined ? false : true;
this.years=af.list('/years/Akhilesh');}
That's the typescript code^
Upvotes: 0
Views: 11443
Reputation: 6354
You have multiple issues going on in your code.
First, since you are moving from using a static array to a call from the database, you must now use an Observable
which will affect your template -- you'll need to pipe through | async
.
(To demonstrate, I'm just going to output the JSON in my example, you will need to adjust for the actual object structure):
<div class="list-group" *ngFor="let year of years | async">
{{ year | json }}
</div>
If you need more about what is going on here, see this part of the Angular Tour of Heros tutorial.
Next, your declaration of years
needs to be adjusted:
years: Observable<any>;
(Ideally, you'd use Finnish Notation to name the Observable, but I'll omit that for consistency with your code).
Naturally, if you haven't already imported it, you'll also need:
import { Observable } from 'rxjs';
Finally, it isn't enough to just store the AngularFireList
object, you have to actually subscribe to the changes. In this case, I'll use snapshotChanges
which gives the full structure including keys, but you could also look at valueChanges
depending on your need. (To access the keys like "1994", you'd want to use year.key
in your template and snapshotChanges
).
this.years=af.list('/years/Akhilesh').snapshotChanges();
I recommend you take a close look at the example in the AngularFire documentation.
Upvotes: 1