Search code examples
angularmean-stack

How to use unsplash to generate different random images within a loop


I created a todo list project which contains an image for each one. I'm using unsplash to generate random images but I'm getting the same image for all of them. How do I get a different image for each task that I create

I'm using the MEAN stack to create a todo list project. I used *ngFor to loop through all the task to display an image for each one on my website but all of them have the same image.

home.component.ts

    ngOnInit() {
      this.componentGetAllTasks();
      this.randomNumber = (Math.floor(Math.random()*10));
  }

  componentGetAllTasks(){
    let obs = this._httpService.serviceGetAllTasks();
    obs.subscribe(data =>{
      console.log('Got all tasks from component', data);
      this.tasks = data['tasks'];
      this.randomNumber()
    })
  }

http.service.ts

  serviceGetAllTasks(){
    return this._http.get('/tasks');
  }

Controller

    all: (req, res)=>{
        Task.find({}, (err, tasks)=>{
            if(err){
                res.json({error: 'Cannot find all tasks', err});
            } else {
                res.json({message: 'Found all tasks!!!', tasks})
            }
        })
    },

HTML

<div class="container card-container task-container">
    <div class="card mb-4"  *ngFor='let task of tasks'>
        <div class="row no-gutters" >
            <div class="col-md-4 gallery">
                <img src="https://source.unsplash.com/random?sig={{randomNumber}}" class="card-img">
            </div>
            <div class="col-md-8 ">
                <div class="card-body"><h5 class="card-title"><input (click)="componentDelete(task._id)" id="delete-me" class="checkbox mr-2" type="checkbox">Title: {{task.title}}</h5>
                    <p class="card-text">Description: {{task.description}}</p>
                    <p class='card-title'>Due Date: <small class='bold'> {{task.dueDate | date:"fullDate"}}</small></p>
                    <button (click)="componentGetTask(task._id)" class="btn btn-primary float-left mr-3">Edit</button>
                    <button class='btn btn-danger'>Add</button>
                </div>
            </div>
        </div>
    </div>
</div>

The outcome I'm trying to succeed is, by using the unsplash website, for each task that is displayed has a different image. Your help is very much appreciated :->


Solution

  • Pham,

    You are generating your random number only once at your component initialization.

    ngOnInit() {
      this.componentGetAllTasks();
      this.randomNumber = (Math.floor(Math.random()*10));
    }
    

    The expression (Math.floor(Math.random()*10)) returns a integer between 0 and 9 and it's stored in this.randomNumber. Bytheway, you cannot run this.randomNumber as a function like you did in the method componentGetAllTasks() because it's not a function.

    So you always get the same image because you only generated the randomNumber once. To fix this, you would need to generate this number for every entry of your tasks. You could have a method that returns a random number

    getRandomNumber() {
      return (Math.floor(Math.random()*10));
    }
    

    and add this method to your template

    <img src="https://source.unsplash.com/random?sig={{getRandomNumber()}}" class="card-img">
    

    Remember that this returns a random number, meaning that you can get the same number multiple times.