0

我是 Sping Boot、rest api 和 angular12 的新手,

我在 vscode 中运行我的程序来调用返回的 api,我收到错误“加载资源失败:服务器响应状态为 404(未找到)”

我的代码:后端控制器:


@RestController
@RequestMapping("/evaluationController/")
public class EvaluationController {
    
    @Autowired
    private EvaluationRepository evaluationrepository;
    
    
    //get all evaluationsnotes
    @CrossOrigin(origins = "http://localhost:4200/")
    @GetMapping("/notes")
    public List<EvaluationModel> getAllEvaluations(){
        return evaluationrepository.findAll();
    }
    
    //post notes
    
    @PostMapping("/notes")
    public EvaluationModel createEvaluationNote(@RequestBody EvaluationModel evaluationNote) {
        return evaluationrepository.save(evaluationNote);
    }
}

我的前端 angular12 服务


@Injectable({
  providedIn: 'root'
})
export class EvaluationserviceService {

private baseUrl!: "http://localhost:8080/evaluationController/notes";
  constructor(private httpClient: HttpClient) { }

  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json'
    })
  }  

getEvaluationNotes():Observable<Evaluationotes[]>{
  return this.httpClient.get<Evaluationotes[]>(`${this.baseUrl}`);
}


}

我的打字稿文件


@Component({
  selector: 'app-fin-evaluation',
  templateUrl: './fin-evaluation.component.html',
  styleUrls: ['./fin-evaluation.component.css']
})
export class FinEvaluationComponent implements OnInit {

  evaluationNote!: Evaluationotes[];

  constructor(private evaluationNoteService: EvaluationserviceService ) { }

  ngOnInit(): void {
    this.getAllNotes();
  }

  private getAllNotes(){
    this.evaluationNoteService.getEvaluationNotes().subscribe(data=>{
      this.evaluationNote = data;
    });
  }

}

谢谢!

4

1 回答 1

0

问题在于baseUrl,您需要使用=(用于初始化)而不是:(在打字稿中用于定义对象类型)。由于您从未真正使用正确的 url 初始化变量,因此请求将转到一些随机 url,例如http://localhost:4200/undefined导致 404。您可以按如下方式更新 url 并尝试:

private baseUrl = "http://localhost:8080/evaluationController/notes";
于 2021-06-13T09:07:55.200 回答