如何在多参数 JSON 数组中执行获取、更新、添加和删除操作,就像 Angular 中的 API 一样

问题描述 投票:0回答:1

我有这个多参数 JSON 数组:

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"
      }
    ];

我曾经有一个API链接。但链接处于非活动状态,我想在我的 service.ts 文件上使用这个

courseList
数组,以便我可以通过反应式角度表单对数组执行相同的获取、更新、添加和删除操作。

所以,我想用

courseList
数组替换 API。通过反应式表单提交,我将数据存储到数组中或从中删除数据或更新数据。新的或更新的数据将与其他以前的数据一起显示在表格上。当然删除的数据就不会存在了。

有单选按钮,可以选择表中的数据之一,然后可以更新或删除数据。

在反应式表单中,我有 4 个字段:

课程名称=>cName

简要描述=>b描述

金额=>金额

持续时间=>持续时间

这是我的其余代码...

课程.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>

抱歉,如果我搞乱了线程。我对这个领域非常陌生。感谢您的帮助。

我尝试将

courseList
数组放入 service.ts 中的
getAllCourses(){}
中,但在 component.ts 文件中
subscriber({})
中的
populatecourses(){}
方法中出现错误。我已将
courseList
数组放入 component.ts 文件中,只是为了避免任何错误并了解结果应该如何。

arrays angular typescript frontend angular-reactive-forms
1个回答
0
投票

您需要的是

of
来自
[rxjs][1]
然后用它来返回
courseList
作为可观察的

  getAllCourses(){
    return of(courseList);
  }
© www.soinside.com 2019 - 2024. All rights reserved.