The Dead Man
The Dead Man

Reputation: 5576

Get object by ID angular 6:

I have simple crud app , which I want user to be able to add comments and comments should be automatically displayed accordingly,

Problems: comments are displayed after refresh and are displayed to other places,

Here is services to get comments and add comments

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { User } from '../model/user.model';
import { Task } from '../model/task.model';
import { Comment } from '../model/comment.model';

@Injectable({
  providedIn: 'root'
})
export class UserService {

  constructor(private http: HttpClient) { }
  taskUrl = 'http://localhost:3000/task';
  commentsUrl = 'http://localhost:3000/comment';
  createTask(task: Task) {
    return this.http.post(this.taskUrl, task);
  }
  getTask() {
    return this.http.get<Task[]>(this.taskUrl);
  }
  addComments(comment: Comment) {
    return this.http.post(this.commentsUrl, comment);
  }
  getComments(id: number) {
    return this.http.get<Comment[]>(this.commentsUrl);
  }
}

Here is componets.ts

import { Component, OnInit } from '@angular/core';
import { Task } from '../model/task.model';
import { Comment } from '../model/comment.model';
import { Router } from '@angular/router';
import { UserService } from '../service/user.service';
import {first} from 'rxjs/operators';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-task-list',
  templateUrl: './task-list.component.html',
  styleUrls: ['./task-list.component.scss']
})
export class TaskListComponent implements OnInit {
tasks: Task[];
comments: Comment[];
  // tslint:disable-next-line:max-line-length
  constructor(private formBuilder: FormBuilder, private router: Router,  private activeRouter: ActivatedRoute, private userService: UserService) { }
  addForm: FormGroup;
  ngOnInit() {
    this.userService.getTask()
      .subscribe( data => {
        this.tasks = data;
      });
      this.activeRouter.params.subscribe((params) => {
        // tslint:disable-next-line:prefer-const
        let id = params['id'];
        this.userService.getComments(id)
        .subscribe(data => {
          this.comments = data;
          });
      });
      this.addForm = this.formBuilder.group({
        id: [],
        author: ['', Validators.required],
        description: ['', Validators.required],
      });
  }
addComments() {
  this.userService.addComments(this.addForm.value)
  .subscribe(data => {
    this.router.navigate(['task-list']);
  });
}
}

Here is html I have for adding and displaying comments

<div class="task-block card">
<div class="task-list" *ngFor="let task of tasks">
  <div class="task-list_header">
    <span>{{task.title}}</span>
  </div>
  <div class="task-list_description">
    <p>{{task.description}}</p>
  </div>
  <div class="task-list_attachment">
    <span>Attachments</span>
  </div>
  <div class="task-list_comments">
    <p>Comments</p>
    <div *ngFor="let comment of comments">
      <ul class="list-group">
        <li class="list-group-item"><label class="text-icon">
            <i class="fa fa-user-circle-o" aria-hidden="true"></i>
          </label> {{comment.author}}</li>
        <li class="list-group-item">{{comment.description}}</li>
      </ul>
      <br>
    </div>
  </div>
  <form [formGroup]="addForm" (ngSubmit)="addComments()">
    <div class="form-group task-group">
      <div class="form-group">
        <label class="">Author</label>
        <input type="text" class="form-control" formControlName="author" id="author" />
      </div>
      <div class="form-group">
          <label class="">Comments</label>
        <textarea class="form-control task-textarea" rows="1" formControlName="description" id="description" ></textarea>
      </div>
    </div>
    <button class="btn btn-default btn-submit">Submit</button>
  </form>
</div>
</div>

Here is json mock up data

{
  "task": [
    {
      "id": 1,
      "title": "profil pracownika ",
      "description": "Task 1, "
    },
    {
      "id": 2,
      "title": "profil pracownika ",
      "description": "Task 2, "
    },
    {
      "id": 2,
      "title": "profil pracownika ",
      "description": "Man utd, "
    }
  ],

  "comment": [
    {
      "id": 1,
      "task_id": 1,
      "author": "Kanczynski",
      "description": "Przegrałes"
    },
    {
      "id": 2,
      "author": "January",
      "description": "eetet"
    }
  ],
  "profile": {
    "name": "typicode"
  }
}

I want comments to be displayed automatically not after refresh, and should be displayed in a specific area where its commented. eg if commented in task one should only be displayed in task one, now display in both tasks

What do I need to change to ge what I want? any help will be apreciated , thanks

Upvotes: 1

Views: 6187

Answers (2)

khan Farman
khan Farman

Reputation: 366

edit this component.ts function

addComments() {
  this.userService.addComments(this.addForm.value)
  .subscribe(data => {
    this.comments.push(this.addForm.value);
  });
 this.router.navigate(['task-list']);
}

Upvotes: 1

Vishal Biradar
Vishal Biradar

Reputation: 1229

Please follow below steps:

Step 1) After adding the new comment, we must add the new comment details to the previous comments list in the component.

Step 2) If you are already in the 'task-list' page, then no need of navigating again to the 'task-list' page.

So after combining the above two steps, we can form the code as below:

 addComments() {
  this.userService.addComments(this.addForm.value)
  .subscribe(data => {
    // hoping the form data matches with your Comments class.
    // so I am directly adding to the list
    // here you can set a variable to check about successfull addition
    this.comments.push(this.addForm.value);
  });
}

So that whenever you add new comment, the list will be refreshed automatically and will show the newly added comment.

Upvotes: 1

Related Questions