【问题标题】:angular 8 application calling Springboot application returns emptyAngular 8 应用程序调用 Springboot 应用程序返回空
【发布时间】:2019-07-15 07:47:27
【问题描述】:

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

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' });
  }
}

course-list.component.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));
  }
}

course-list.component.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));
      }

}

【问题讨论】:

  • 嗨@user21334,关于“courses.services.ts”你可以尝试将baseUrl更改为“localhost:8080/courses”,而不仅仅是“/courses/”。另外,您的“course-list.component.ts”我看不到调用后端的 reloadData() 调用,不应该在 ngOnInit 内?
  • 角跑开发模式是否使用ng serve ?

标签: angular spring-boot


【解决方案1】:

下面的代码

  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();
}

【讨论】:

    【解决方案2】:

    你还没有初始化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>
    

    【讨论】:

      猜你喜欢
      • 2017-03-08
      • 2022-01-25
      • 1970-01-01
      • 1970-01-01
      • 2020-06-13
      • 1970-01-01
      • 2017-12-03
      • 2020-02-22
      • 2017-07-16
      相关资源
      最近更新 更多