Search code examples
angularrxjs-observables

Why I am unable to display Observable data in my HTML page?


dashbord.component.ts As I got data in books$ : Observable<Student[]> but I am unable to show in HTML

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import {Student} from '../models/student'
import {StudentService} from '../services/student.service'

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

  books$ : Observable<Student[]>
  constructor(private studentservice:StudentService) { }

  ngOnInit(): void {
    const id=localStorage.getItem("studentRollno");
    console.log(id);
    this.books$=this.studentservice.getStudentBooks(localStorage.getItem(id));
    console.log(this.books$);
  }

}

HTML This is the HTML code I use Pipe as async but still unable to show data in html page. Plz, help if possible.

<ul  *ngIf="books$ | async as books" style="list-style-type:none">
    <li *ngFor="let item of books">
        <div class="card" style="width: 18rem;">
            <div class="card-body">
                <h5 class="card-title">{{item.name}}</h5>  
            </div>
        </div>
    </li>
</ul>

I call It in my service.ts file I get data from here

getStudentBooks(id) : Observable<Student[]>{
     return this.http.get<Student[]>(`http://localhost:3000/student/getdata/${id}`);
  }

In node file at backend I use

router.get('/getdata/:id', async (req, res) => {
  const studentRollno=req.params.id;
  try {
    const studentBooks = await BookissuedSchema.find({rollno:studentRollno});
    res.send(studentBooks);
  } catch (error) {
    res.send(error); 
  }
})

Please Help If possible


Solution

  • Two things:

    1. this.studentservice.getStudentBooks(localStorage.getItem(id)); looks wrong, should it be this.studentservice.getStudentBooks(id) instead?;
    2. You're destructively reassigning your observable oninit, but assignment only needs to happen once on component creation. Move that logic to the constructor.
    import { Component, OnInit } from '@angular/core';
    import { Observable } from 'rxjs';
    import {Student} from '../models/student'
    import {StudentService} from '../services/student.service'
    
    @Component({
      selector: 'app-dashbord',
      templateUrl: './dashbord.component.html',
      styleUrls: ['./dashbord.component.css']
    })
    export class DashbordComponent implements OnInit {
    
      public readonly books$: Observable<Student[]>
    
      constructor(private readonly studentservice: StudentService) {
        const id = localStorage.getItem("studentRollno");
        this.books$ = this.studentservice.getStudentBooks(id);
      }
    
      ngOnInit(): void {}
    
    }