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

时间:2019-07-15 07:47:27

标签: angular spring-boot

我有一个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

@Injectable()
export class JwtInterceptor implements HttpInterceptor {
    constructor(private userContext: UserContext) { }

intercept(
    request: HttpRequest<any>,
    next: HttpHandler
): Observable<HttpEvent<any>> {
    const authToken = this.userContext.getToken();
    if (!!authToken) {
        request = request.clone({
            setHeaders: {
                Authorization: `Bearer ${authToken}`
            }
        });
    }

    return next.handle(request);
    }
}

course-list.component.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.html

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

SpringBoot应用程序控制器

<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>

2 个答案:

答案 0 :(得分:2)

下面的代码

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

答案 1 :(得分:0)

您尚未初始化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>