我正在学习使用Angular的Spring启动,我正在努力让我的第一个应用程序运行并阅读以下博客:
http://mydevgeek.com/angular-4-crud-application-with-spring-boot-rest-service-part-2/
https://dzone.com/articles/build-a-basic-crud-app-with-angular-50-and-spring
我设法让应用程序在8080端口上使用spring boot工作,并且按预期工作。但是,当我尝试使用Angular时,我收到以下错误:
Angular is running in the development mode. Call enableProdMode() to enable the production mode.
core.js:3675
ERROR
{…}
error: error
bubbles: false
cancelBubble: false
cancelable: false
composed: false
currentTarget: null
defaultPrevented: false
eventPhase: 0
explicitOriginalTarget: XMLHttpRequest
__zone_symbol__errorfalse: null
__zone_symbol__loadfalse: null
__zone_symbol__xhrListener: function scheduleTask/target[XHR_LISTENER]()
__zone_symbol__xhrSync: false
__zone_symbol__xhrTask: Object { runCount: 0, _state: "notScheduled", type: "macroTask", … }
__zone_symbol__xhrURL: "//localhost:8080/cool-cars"
mozAnon: false
mozSystem: false
readyState: 4
response: ""
responseText: ""
responseType: "text"
responseURL: ""
status: 0
statusText: ""
timeout: 0
upload: XMLHttpRequestUpload { }
withCredentials: false
__proto__: XMLHttpRequestPrototype { open: patchMethod/proto[name](), setRequestHeader: setRequestHeader(), send: patchMethod/proto[name](), … }
isTrusted: true
lengthComputable: false
loaded: 0
originalTarget: XMLHttpRequest
__zone_symbol__errorfalse: null
__zone_symbol__loadfalse: null
__zone_symbol__xhrListener: function scheduleTask/target[XHR_LISTENER]()
__zone_symbol__xhrSync: false
__zone_symbol__xhrTask: Object { runCount: 0, _state: "notScheduled", type: "macroTask", … }
__zone_symbol__xhrURL: "//localhost:8080/cool-cars"
mozAnon: false
mozSystem: false
readyState: 4
response: ""
responseText: ""
responseType: "text"
responseURL: ""
status: 0
statusText: ""
timeout: 0
upload: XMLHttpRequestUpload { }
withCredentials: false
__proto__: XMLHttpRequestPrototype { open: patchMethod/proto[name](), setRequestHeader: setRequestHeader(), send: patchMethod/proto[name](), … }
target: XMLHttpRequest { __zone_symbol__xhrSync: false, __zone_symbol__xhrURL: "//localhost:8080/cool-cars", readyState: 4, … }
timeStamp: 5395.150856236699
total: 0
type: "error"
__proto__: ProgressEventPrototype { lengthComputable: Getter, loaded: Getter, total: Getter, … }
headers: Object { normalizedNames: Map, lazyUpdate: null, headers: Map }
message: "Http failure response for (unknown url): 0 Unknown Error"
name: "HttpErrorResponse"
ok: false
status: 0
statusText: "Unknown Error"
url: null
__proto__: Object { constructor: HttpErrorResponse() }
当我查看网络标签时,我看到以下信息:
部首:
接受
application / json,text / plain, /
接受编码
gzip,deflate
接受语言
FR,FR-FR; Q = 0.8,的en-US; Q = 0.5,连接; Q = 0.3
连接
活着
主机
本地主机:8080
请求网址:http://localhost:8080/cool-cars 请求方法:GET
但没有回应。似乎请求超时了。
Chrome网络标签显示:
Request URL:http://localhost:8080/cool-cars
Referrer Policy:no-referrer-when-downgrade
Provisional headers are shown
Accept:application/json, text/plain, */*
Origin:http://localhost:4200
Referer:http://localhost:4200/
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.119 Safari/537.36
我的Java课程:
汽车类:
import lombok.*;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;
import javax.persistence.Entity;
@Entity
@Getter @Setter
@NoArgsConstructor
@ToString @EqualsAndHashCode
public class Car {
@Id @GeneratedValue
private Long id;
private @NonNull String name;
}
汽车储存库:
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import org.springframework.web.bind.annotation.CrossOrigin;
@RepositoryRestResource
@CrossOrigin(origins = "http://localhost:4200")
public interface CarRepository extends JpaRepository<Car, Long> {
}
控制器:
import java.util.Collection;
import java.util.stream.Collectors;
@CrossOrigin(origins = "http://localhost:4200")
@RestController
@RequestMapping("/")
public class CoolCarController {
private CarRepository repository;
public CoolCarController(CarRepository repository) {
this.repository = repository;
}
@GetMapping("/cool-cars")
public Collection<Car> coolCars() {
return repository.findAll().stream()
.filter(this::isCool)
.collect(Collectors.toList());
}
private boolean isCool(Car car) {
return !car.getName().equals("AMC Gremlin") &&
!car.getName().equals("Triumph Stag") &&
!car.getName().equals("Ford Pinto") &&
!car.getName().equals("Yugo GV");
}
}
App类:
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
ApplicationRunner init(CarRepository repository) {
return args -> {
Stream.of("Ferrari", "Jaguar", "Porsche", "Lamborghini", "Bugatti",
"AMC Gremlin", "Triumph Stag", "Ford Pinto", "Yugo GV").forEach(name -> {
Car car = new Car();
car.setName(name);
repository.save(car);
});
repository.findAll().forEach(System.out::println);
};
}
}
如您所见,CORS启用了注释。
在Angular中,我做了以下更改。
car.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class CarService {
constructor(private http: HttpClient) { }
getAll(): Observable<any> {
return this.http.get('//localhost:8080/cool-cars');
}
}
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { CarService } from './shared/car/car.service';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
import {CarListComponent} from "./car-list/car-list.component";
@NgModule({
declarations: [
AppComponent,
CarListComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [CarService],
bootstrap: [AppComponent]
})
export class AppModule { }
汽车清单组件:
import { Component, OnInit } from '@angular/core';
import { CarService } from '../shared/car/car.service';
@Component({
selector: 'app-car-list',
templateUrl: './car-list.component.html',
styleUrls: ['./car-list.component.css']
})
export class CarListComponent implements OnInit {
cars: Array<any>;
constructor(private carService: CarService) { }
ngOnInit() {
this.carService.getAll().subscribe(data => {
this.cars = data;
});
}
}
汽车清单组件html
<h2>Car List</h2>
<div *ngFor="let car of cars">
{{car.name}}
</div>
我正在使用IntelliJ。
我已经阅读了很多关于这个问题的内容,包括关于这个主题的类似问题,但是我没有看到可以解决这个问题的答案(并且具有相同的空响应)。非常感谢您的帮助!