Search code examples
arraysangulartypescriptfrontendangular-reactive-forms

How to perform get, update, add and delete operation in a multi-parameter JSON array just like an API in Angular


I have this multi-parameter JSON array:

public courseList:any=[
      {
        id:1,
        cName: "Angular",
        bDesc: "This is the basic course for Angular.",
        amt: "$50",
        dur: "120 Hours"
      },
      {
        id:2,
        cName: "React",
        bDesc: "This is the basic course for React.",
        amt: "$55",
        dur: "125 Hours"
      },
      {
        id:3,
        cName: "MEAN Stack",
        bDesc: "This is the basic course for MEAN Stack.",
        amt: "$100",
        dur: "160 Hours"
      },
      {
        id:4,
        cName: "MERN Stack",
        bDesc: "This is the basic course for MERN Stack.",
        amt: "110",
        dur: "155 Hours"
      },
      {
        id:5,
        cName: "Full Stack",
        bDesc: "This is the basic course for Full Stack.",
        amt: "$180",
        dur: "180 Hours"
      }
    ];

I used to have an API link. But the link being inactive, I want to use this courseList array on my service.ts file so that I can perform same get, update, add and delete operation into the array through a Reactive Angular Form.

So, I want to replace the API with courseList array. And through a Reactive Form submission I store the data into the array or remove the data from it or update the data. and that new or updated data will show on the table along with other previous ones. Of course the deleted data won't be there.

There are Radio buttons by which one of the data from the table can be selected and then the data can be updated or deleted.

In the Reactive Form I have 4 fields:

Course Name=>cName

Brief Description=>bDesc

Amount=>amt

Duration=>dur

Here is the rest of my codes...

course.service.ts

export class CourseService {

  constructor(private http:HttpClient) { }
  // All courses related API will be here
  private Base_Url:string = ""
  getAllCourses(){
    return this.http.get(`${this.Base_Url}`);
  }
  // Add Course Data
  addCourseData(Data:any){
    return this.http.post(`${this.Base_Url}`,Data);
  }
  // Update Course Data
  updateCourseData(ID:any,Data:any){
    return this.http.put(`${this.Base_Url}${ID}`,Data);
  }
  // Delete Course Data
  deleteCourseData(ID:any){
    return this.http.delete(`${this.Base_Url}${ID}`)
  }
}

admin.component.ts

export class AdminComponent {
  public page:number=1;
  public courseList:any=[
      {
        id:1,
        cName: "Angular",
        bDesc: "This is the basic course for Angular.",
        amt: "$50",
        dur: "120 Hours"
      },
      {
        id:2,
        cName: "React",
        bDesc: "This is the basic course for React.",
        amt: "$55",
        dur: "125 Hours"
      },
      {
        id:3,
        cName: "MEAN Stack",
        bDesc: "This is the basic course for MEAN Stack.",
        amt: "$100",
        dur: "160 Hours"
      },
      {
        id:4,
        cName: "MERN Stack",
        bDesc: "This is the basic course for MERN Stack.",
        amt: "110",
        dur: "155 Hours"
      },
      {
        id:5,
        cName: "Full Stack",
        bDesc: "This is the basic course for Full Stack.",
        amt: "$180",
        dur: "180 Hours"
      }
    ];
    public selectedCourseData:any=[];
    public courseData!:FormGroup;
  constructor(private cService:CourseService,private fbuilder:FormBuilder) {
    this.courseData=this.fbuilder.group({
      'name':[''],
      'desc':[''],
      'amnt':[''],
      'durn':['']
    });
  }
  ngOnInit() {
    // now call the populateCourses()
    this.populateCourses();
  }
  
  // Populate all Courses
  populateCourses(){
    this.cService.getAllCourses().subscribe({
      next:((res:any)=>{
        console.log(res);
        this.courseList=res;
      }),
      error:((error:any)=>{
        console.log(error);
      }),
      complete:(()=>{
        console.log('Calling Successful');
      })
    });
  }

  //Posting Course Details to Database
  AddCourse(){
    console.log(this.courseData.value);
    let uploadData=new FormData();
    uploadData.append('cName',this.courseData.get('name')?.value);
    uploadData.append('bDesc',this.courseData.get('desc')?.value);
    uploadData.append('amt',this.courseData.get('amnt')?.value);
    uploadData.append('dur',this.courseData.get('durn')?.value);
    // now posting FormData: uploadData
    this.cService.addCourseData(uploadData).subscribe({
      next:((res:any)=>{
        console.log (res);
        // calling all  courses again for updating UI with new data
        this.populateCourses();
      }),
      error:((error)=>{
        console.log(error);
      }),
      complete:(()=>{
        console.log('post calling successful');
      })
    });

    //  Resetting the form after submission
    this.courseData.reset();
  }

  // Selecting Course Data
  select(cData:any){
    console.log(cData);
    this.selectedCourseData=cData;
    // now setting all cData
    this.courseData.get('name')?.setValue(this.selectedCourseData.cName);
    this.courseData.get('desc')?.setValue(this.selectedCourseData.bDesc);
    this.courseData.get('amnt')?.setValue(this.selectedCourseData.amt);
    this.courseData.get('durn')?.setValue(this.selectedCourseData.dur);
  }

  // updating course details in database
  UpdateCourse(){
    let uploadData=new FormData();
    uploadData.append('cName',this.courseData.get('name')?.value);
    uploadData.append('bDesc',this.courseData.get('desc')?.value);
    uploadData.append('amt',this.courseData.get('amnt')?.value);
    uploadData.append('dur',this.courseData.get('durn')?.value);
    // now getting ID and Update Course Data
    let Id=this.selectedCourseData.id;
    console.log(Id);
    this.cService.updateCourseData(Id,uploadData).subscribe({
      next:((res)=>{
        console.log(res);
        // populate Courses Data
        this.populateCourses();
      }),
      error:((error)=>{
        console.log(error);
      }),
      complete:(()=>{
        console.log('Update Course Data Successful');
      })
    });
    // Resetting the Form
    this.courseData.reset();
  }

  // Deleting selected course from Database
  DeleteCourse(){
    let Id=this.selectedCourseData.id;
    console.log(Id);
    var result = confirm("want to delete the course?");
    if (result) {}
    // now Delete Course Data
    this.cService.deleteCourseData(Id).subscribe({
      next:((res)=>{
        console.log(res);
        // populate Courses Data
        this.populateCourses();
      }),
      error:((error)=>{
        console.log(error);
      }),
      complete:(()=>{
        console.log('Delete Course Data Successful');
      })
    });
    // Resetting the Form
    this.courseData.reset();
  }
}

admin.component.html

<div class="container-fluid">
    <header class="jumbotron">
        <h1 align="center">Admin Panel</h1>
    </header>
    <main>
        <div class="row">
            <div class="col-lg-8 border-right">
                <header class="modal-header">
                    <h2 align="center">All Course List</h2>
                </header>
                <hr>
                <table class="table table-hover-table-bordered">
                    <tr>
                        <th><strong>#</strong></th>
                        <th><strong>Course Name</strong></th>
                        <th><strong>Brief Description</strong></th>
                        <th><strong>Amount</strong></th>
                        <th><strong>Duration</strong></th>
                    </tr>
                    <tr *ngFor="let c of courseList | paginate:{itemsPerPage:10, currentPage:page}">
                        <td>
                            <input type="radio" name="radio" (click)="select(c)">
                        </td>
                        <td>{{c.cName}}</td>
                        <td>{{c.bDesc}}</td>
                        <td>{{c.amt}}</td>
                        <td>{{c.dur}}</td>
                    </tr>
                </table>
                <pagination-controls (pageChange)="page = $event"></pagination-controls>
            </div>
            <div class="col-lg-4">
                <header class="modal-header">
                    <h2 align="center">Course Management</h2>
                </header>
                <form [formGroup]="courseData">
                    <div class="form-group">
                        <label>Course Name</label>
                        <input type="text" formControlName="name" class="form-control">
                    </div>
                    <div class="form-group">
                        <label>Brief Description</label>
                        <textarea rows="10" col="20" formControlName="desc" class="form-control"></textarea>
                    </div>
                    <div class="form-group">
                        <label>Amount</label>
                        <input type="text" formControlName="amnt" class="form-control">
                    </div>
                    <div class="form-group">
                        <label>Duration</label>
                        <input type="text" formControlName="durn" class="form-control">
                    </div>
                    <div class="form-group">
                        <section *ngIf="selectedCourseData==0">
                            <button class="btn btn-sm btn-outline-success" (click)="AddCourse()">Add New Course</button>
                        </section>
                        <section *ngIf="selectedCourseData!=0">
                            <button class="btn btn-sm btn-outline-info" (click)="UpdateCourse()">Update Course</button>
                            <button class="btn btn-sm btn-outline-danger" (click)="DeleteCourse()">Delete Course</button>
                        </section>
                    </div>
                </form>
            </div>
        </div>
    </main>
</div>

Sorry, if I messed up the thread. I'm very much new to this field. Appreciate your help.

I've tried putting courseList array into the getAllCourses(){} in service.ts but it gives error in the subscriber({}) method in populatecourses(){} in component.ts file. I have put the courseList array into the component.ts file just to avoid any error and to have an idea how the result should look.


Solution

  • what you need is of from https://rxjs.dev/api/index/function/of then use that to return the courseList as an observable

      getAllCourses(){
        return of(courseList);
      }