How to Toggle a `<mat-icon>` after reading a favorites array from the API

197 Views Asked by At

I am working on a project for a program I'm in, and I currently have a hiccup in my assignment. I am using Angular to build the program, and I have a small API I built to pull data from. The goal: to toggle the `favorite` to `favorite_border` according to whether the Item (in this case a movie) has been added to the user's `FavoriteMovies` collection.

The HTML snippet:

<mat-icon
  *ngIf="!inFavorites(movie._id)"
  (click)="addFavMovie(
    movie._id,
    movie.Title)"
>
  favorite_border
</mat-icon>
<mat-icon
  *ngIf="inFavorites(movie._id)"
  (click)="removeFavMovie(
    movie._id,
    movie.Title
  )"
 >
   favorite
 </mat-icon>

Some of the code from my `.ts` file:

export class MovieCardComponent implements OnInit {
  movies: any[] = [];
  genres: any[] = [];
  favorites: any[] = [];

  constructor(
    public fetchApiData: FetchApiDataService,
    public dialog: MatDialog,
    public snackBar: MatSnackBar,
  ) { }

  ngOnInit(): void {
    this.getMovies();
    this.getFav();
  }

  getMovies(): void {
    this.fetchApiData.getAllMovies().subscribe((resp: any) => {
      this.movies = resp;
      return this.movies;
    })
  }

  getFav(): void {
    const user = localStorage.getItem('user');
    this.fetchApiData.getUser(user).subscribe((resp: any) => {
      this.favorites = resp.FavoriteMovies;
      return (this.favorites);
    });
  }
...

  addFavMovie(movieId: string, title: string): void {
    this.fetchApiData.addFavoriteMovies(movieId).subscribe((resp: any) => {
      console.log(resp);
      this.snackBar.open(`You added ${title} to your favorites list`, 'OK', {
        duration: 4000,
      });
      this.ngOnInit();
    });
   
    return this.getFav();
  }

  removeFavMovie(movieId: any, title: string): void {

    this.fetchApiData.deleteMovie(movieId).subscribe((resp: any) => {
      console.log(resp);
      this.snackBar.open(`You successfully removed ${title} from your favorites list`, 'OK', {
        duration: 4000,
      });
    });
    this.ngOnInit();
    return this.getFav();
  }

  inFavorites(movieId: any): boolean {
    if (this.favorites.indexOf(movieId) > -1) {
      return true;
    } else {
      return false;
    }
  }

And finally, the routing of the API in the `fetch-api-data.services`

getUser(username: any): Observable<any> {
    const token = localStorage.getItem('token');
    return this.http.get(apiUrl + 'users/' + username, {
      headers: new HttpHeaders(
        {
          Authorization: 'Bearer ' + token,
        })
    }).pipe(
      map(this.extractResponseData),
      catchError(this.handleError)
    );
  }

    // Making the API call for calling a list of the user's favorite movies
  getFavoriteMovies(username:any): Observable<any> {
    const token = localStorage.getItem('token');
    return this.http.get(apiUrl + 'users/' + username + '/movies', {
      headers: new HttpHeaders(
        {
          Authorization: 'Bearer ' + token,
        })
    }).pipe(
      map(this.extractResponseData),
      catchError(this.handleError)
    );
  }

  // Making the API call for adding movies to profile
  addFavoriteMovies(movieId:any): Observable<any> {
    const username = localStorage.getItem('user')
    const token = localStorage.getItem('token');
    return this.http.post(apiUrl + 'users/' + username + '/movies/' + movieId, null, {
      headers: new HttpHeaders(
        {
          Authorization: 'Bearer ' + token,
        })
    }).pipe(
      map(this.extractResponseData),
      catchError(this.handleError)
    );
  }

Last, but not least, if this is not enough to help me toggle the icon, here is my GitHub repository for anyone that might be able to help out: https://github.com/zeusrahl/myFlix-Angular-client. I know that there are other issues with my code, but right now, my focus is on the "add favorites" or "remove favorites" from the user, so that it can be read by the main page (as well as the user's profile page). Thank you in advanced.

1

There are 1 best solutions below

0
Ethan On

This issue was resolved. It seemed my inFavorites function was attempting to work as if this.favorites was an array, and all I needed to pass was the API's ._id. Here is the area of code that needed to be fixed:

getFav(): void {
    const user = localStorage.getItem('user');
    this.fetchApiData.getUser(user).subscribe((resp: any) => {
      this.favorites = resp.FavoriteMovies.map((x: any) => x._id);
      console.log(this.favorites);
      return (this.favorites);
    });
  }