0

I am building an Angular portfolio using a fake backend as an interceptor. The app in general has no issues but only when it comes to data persisting I find a bug. In the "home" page I get a Nasa picture and a like button. The picture comes from Nasa’s API. This Like Button saves the current image, the currentuser and the number of likes. It’s an object that I send to my fakebackend so later I can fetch them. Something like this:

The like model:

export interface LikeObject {

    picture: string;
    username: string;
    likes: number;

}

DayPictureComponent HTML:

<mat-card class="mat-elevation-z8" >
        <mat-card-title>{{ p.title }}</mat-card-title>
        <mat-card-subtitle>Date: {{ p.date }}</mat-card-subtitle>
        <img mat-card-image src="{{ p.url }}" alt="{{p.title}}" />
        <mat-card-content>
          <button type="button" (click)="like(p.url)" class="btn btn-danger">Like</button>
           //this is the button where all begings
        </mat-card-content>

      </mat-card>

DayPictureComponent TS

ngOnInit(): void {
   
    this.nasaService.getPictures()
    .subscribe((pics:LikeObject[])=>{
      this.picsToDisplay=pics;
     console.log(this.picsToDisplay)
    })
  }

like(pic){

    let likeObject: LikeObject={
      picture:pic,
      username:this.user.username,
      likes: this.likes++
    }

    this.nasaService.likeDayPic(likeObject)
    .subscribe(()=>{})

  }

The NASA service:

//FAKEBACKEND

likeDayPic(likeObject: LikeObject){
  console.log(likeObject)
  return this.http.post('/likedaypic',likeObject)
}
getPictures(): Observable<LikeObject[]>{
  return this.http.get<LikeObject[]>('/pictures');
}

And finally the HTML chunk where I hope to see the previous images and names I saved in the past:

DayPicture HTML (same file, but in the bottom row)

 <div class="row" style="margin-top: 20px;" *ngFor="let p of picsToDisplay">
    <div class="col-md-6" >
      <h1 class="heading">Our user's favourite pictures</h1>
      <div class="card mat-elevation-z8" style="width: 18rem;">
        <img class="card-img-top" src="{{p.picture}}" alt="Card image cap">
        <div class="card-body">
          <h5 class="card-title">By {{p.username}}</h5>
          <p class="card-text">Likes: {{p.likes}}</p>
          <button type="button"class="btn btn-primary">Go somewhere</button>
        </div>
      </div>
    </div>
  </div>

The issue is that I only see the saved Object rendered in this bootstrap card when I click the like button, which is fine. But what about the previous likes? Supposedly they are stored in an localstorage array in the backend file…So I’m a bit lost. I’m missing something but I can’t figure out what. Any ideas, please?

Anonymous Asked question May 14, 2021