angular 8 应用程序调用 Springboot 应用程序返回空



我有一个 Springboot 应用程序,它返回课程 http://localhost:8080/courses/列表。我有一个 Angular 应用程序,它调用提到的 API 以便在前端显示这些课程。我可以确认 springboot 应用程序正在返回值。但不知何故,我的角度应用程序似乎无法从角度应用程序中检索相同的内容。下面是代码。

弹簧启动应用程序的输出

[{"_id":"5d29c3a58212eda90db024c4","courseID":"1","courseName":"C#"},{"_id":"5d29c3a58212eda90db024c5","courseID":"2","courseName":"Java"},{"_id":"5d29c3a58212eda90db024c6","courseID":"3","courseName":"JavaScript"}]

courses.services.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class CoursesService {
  private baseURL = "/courses/";
  constructor(private http: HttpClient) { }
  getCoursesList(): Observable<any> {
    return this.http.get('${this.baseURL}');
  }
  deleteCourse(id: number): Observable<any> {
    return this.http.delete(`${this.baseURL}/${id}`, { responseType: 'text' });
  }
}

课程列表.组件.ts

import { Component, OnInit } from '@angular/core';
import { CoursesService } from '../courses.service';
import { Courses } from '../courses';
import { Observable } from 'rxjs';
@Component({
  selector: 'app-course-list',
  templateUrl: './course-list.component.html',
  styleUrls: ['./course-list.component.css']
})
export class CourseListComponent implements OnInit {
  courses: Observable<Courses[]>;
  constructor(private coursesService: CoursesService) { }

  ngOnInit() {
  }
  reloadData() {
    this.courses = this.coursesService.getCoursesList();
  }
  deleteCourse(id: number) {
    this.coursesService.deleteCourse(id)
      .subscribe(
        data => {
          console.log(data);
          this.reloadData();
        },
        error => console.log(error));
  }
}

课程列表组件.html

<div class="panel panel-default">
  <div class="panel-heading">
    <h1>Courses</h1>
  </div>
  <div class="panel-body">
    <table class="table table-striped table-bordered">
      <thead>
        <tr>
          <th>Id</th>
          <th>Course ID</th>
          <th>Course Name</th>
          <th>Actions</th>
        </tr>
      </thead>
      <tbody>
        <tr *ngFor="let course of courses">
          <td>{{course.id}}</td>
          <td>{{course.courseId}}</td>
          <td>{{course.courseName}}</td>
          <td><button (click)="deleteEmployee(employee.id)">Delete</button></td>
        </tr>
      </tbody>
    </table>
  </div>
</div>

SpringBoot 应用程序控制器

package SpringBoot.Training.Management.Tool.SpringBootTMTCourses.Controller;
import java.util.List;
import javax.validation.Valid;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import SpringBoot.Training.Management.Tool.SpringBootTMTCourses.Model.Courses;
import SpringBoot.Training.Management.Tool.SpringBootTMTCourses.Repository.CoursesRepository;
@RestController
@CrossOrigin(origins = "http://localhost:4200")
@RequestMapping("/courses")
public class CourseController {
    @Autowired
    private CoursesRepository repository;
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public List<Courses> getAllCourses() {
      return repository.findAll();
    }
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Courses getCourseById(@PathVariable("id") ObjectId id) {
      return repository.findBy_id(id);
    }

      @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
      public void modifyCourseById(@PathVariable("id") ObjectId id, @Valid @RequestBody Courses pets) {
        pets.set_id(id);
        repository.save(pets);
      }
      @RequestMapping(value = "/", method = RequestMethod.POST)
      public Courses createPet(@Valid @RequestBody Courses pets) {
        pets.set_id(ObjectId.get());
        repository.save(pets);
        return pets;
      }
      @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
      public void deletePet(@PathVariable ObjectId id) {
        repository.delete(repository.findBy_id(id));
      }
}

下面的代码

  reloadData() {
    this.courses = this.coursesService.getCoursesList();
  }

应该是

  reloadData() {
    this.coursesService.getCoursesList().subscribe((res)=>{
            console.log(res);
            this.courses =res;
        });
  }

课程属性的类型应为:

courses: Courses[];

然后,在 ngOnInit(( 中调用 reloadData((,因为它的属性没有被设置。

ngOnInit() {
    this.reloadData();
}

您尚未初始化courses 。在你的ngOnInit中这样做

import { Component, OnInit } from '@angular/core';
import { CoursesService } from '../courses.service';
import { Courses } from '../courses';
import { Observable } from 'rxjs';
@Component({
  selector: 'app-course-list',
  templateUrl: './course-list.component.html',
  styleUrls: ['./course-list.component.css']
})
export class CourseListComponent implements OnInit {
  courses: Observable<Courses[]>;
  constructor(private coursesService: CoursesService) { }

  ngOnInit() {
    this.reloadData();  // HERE
  }
  reloadData() {
    this.courses = this.coursesService.getCoursesList();
  }
  deleteCourse(id: number) {
    this.coursesService.deleteCourse(id)
      .subscribe(
        data => {
          console.log(data);
          this.reloadData();
        },
        error => console.log(error));
  }
}

现在,由于this.coursesService.getCoursesList();将返回一个Observable,因此您必须在模板中使用async管道才能解包该值。像这样:

<div class="panel panel-default">
  <div class="panel-heading">
    <h1>Courses</h1>
  </div>
  <div class="panel-body">
    <table class="table table-striped table-bordered">
      <thead>
        <tr>
          <th>Id</th>
          <th>Course ID</th>
          <th>Course Name</th>
          <th>Actions</th>
        </tr>
      </thead>
      <tbody>
        <tr *ngFor="let course of courses | async">
          <td>{{course.id}}</td>
          <td>{{course.courseId}}</td>
          <td>{{course.courseName}}</td>
          <td><button (click)="deleteEmployee(employee.id)">Delete</button></td>
        </tr>
      </tbody>
    </table>
  </div>
</div>

最新更新