Как функциональность в MEAN STACK - Angular Node Express Mongodb не работает - PullRequest
0 голосов
/ 21 октября 2019

Я создаю дискуссионный форум, на котором пользователь может публиковать блоги, нравится или не нравиться каждому блогу, а также комментировать его. Но у меня возникла проблема с функциональностью Нравится / Не нравится. Я использую Angular, Node и MongoDB. При нажатии кнопки «лайк» должна работать функция приращения, и на странице должны отображаться текущие лайки для данного сообщения.

   // Function to get all blogs from the database
   getAllBlogs() {
    // Function to GET all blogs from database
    this.blogService.getAllBlogs().subscribe(data => {
      this.blogPosts = data.blogs; // Assign array to use in HTML
    });
  }

  likeBlog(id) {
    // Service to like a blog post
    this.blogService.likeBlog(id).subscribe(data => {
      this.getAllBlogs(); // Refresh blogs after like
    });
  }

  // Function to disliked a blog post
  dislikeBlog(id) {
    // Service to dislike a blog post
    this.blogService.dislikeBlog(id).subscribe(data => {
      this.getAllBlogs(); // Refresh blogs after dislike
    });
  }
blog.component.html:

   <div class="panel-footer">
        <strong>Posted by: </strong>{{ currentBlog.username }}
        <br />
        <strong>Date: </strong>{{ currentBlog.modifiedDate | date}}
        <br />
        <div *ngIf="username == currentBlog.username">
          <strong>Likes: </strong>{{ currentBlog.likes }}
          <br />
          <strong>Dislikes: </strong>{{ currentBlog.dislikes }}
        </div>
  
  
        <div *ngIf="username != currentBlog.username">
        <div class="dropdown">
         
          <button [disabled]="currentBlog.likedBy.indexOf(username) > -1"  type="button" name="button" class="btn btn-sm btn-success" (click)="likeBlog(currentBlog._id)"><span class="glyphicon glyphicon-thumbs-up">&nbsp;</span>Likes: {{ currentBlog.likes }}</button>
         
          <div class="dropdown-content">
            <a *ngFor="let liker of currentBlog.likedBy">{{ liker }}</a>
          </div>
        </div>

blog.service.ts:


  likeBlog(id) {
    let headers = new Headers;
    headers.append('Content-Type', 'application/json');
    this.token = localStorage.getItem('id_token');
    headers.append('Authorization', this.token);
    const blogData = { id: id };
    return this.http.put('http://' + this.serverAddress +  'blogs/likeBlog/', blogData, { headers: headers }).pipe(
      map(res => res.json()));
    }
  
  // Function to dislike a blog post
  dislikeBlog(id) {
    let headers = new Headers;
    headers.append('Content-Type', 'application/json');
    this.token = localStorage.getItem('id_token');
    headers.append('Authorization', this.token);
    const blogData = { id: id };
    return this.http.put('http://' + this.serverAddress +  'blogs/dislikeBlog/', blogData, { headers: headers }).pipe(
      map(res => res.json()));
    }
  

routes/blog.js

router.put('/likeBlog', passport.authenticate('jwt', { session: false }), (req, res, next) => {
   
    if (!req.body.id) {
      res.json({ success: false, message: 'No id was provided.' }); 
    } else {
    
      Blog.findOne({ _id: req.body.id }, (err, blog) => {
      
        if (err) {
          res.json({ success: false, message: 'Invalid blog id' });
        } else {
         
          if (!blog) {
            res.json({ success: false, message: 'That blog was not found.' }); 
          } else {
           
            User.findOne({ _id: req.decoded.userId }, (err, user) => {
            
              if (err) {
                res.json({ success: false, message: 'Something went wrong.' }); 
              } else {
                
                if (!user) {
                  res.json({ success: false, message: 'Could not authenticate user.' });
                } else {
                 
                  if (user.username === blog.username) {
                    res.json({ success: false, messagse: 'Cannot like your own post.' }); 
                  } else {
                   
                    if (blog.likedBy.includes(user.username)) {
                      res.json({ success: false, message: 'You already liked this post.' }); // Return error message
                    } else {
                      // Check if user who liked post has previously disliked a post
                      if (blog.dislikedBy.includes(user.username)) {
                        blog.dislikes--;
                        const arrayIndex = blog.dislikedBy.indexOf(user.username); 
                        blog.dislikedBy.splice(arrayIndex, 1);
                        blog.likes++; 
                        blog.likedBy.push(user.username); 
                      
                        blog.save((err) => {
                         
                          if (err) {
                            res.json({ success: false, message: 'Something went wrong.' }); 
                          } else {
                            res.json({ success: true, message: 'Blog liked!' }); 
                          }
                        });
                      } else {
                        blog.likes++;
                        blog.likedBy.push(user.username); 
                        blog.save((err) => {
                          if (err) {
                            res.json({ success: false, message: 'Something went wrong.' }); 
                          } else {
                            res.json({ success: true, message: 'Blog liked!' }); 
                          }
                        });
                      }
                    }
                  }
                }
              }
            });
          }
        }
      });
    }
  });
...