简体   繁体   English

无法从 Angular 调用 REST API 到 Spring REST 控制器

[英]Not able to make rest API call from Angular to Spring REST controller

I'm trying to make a rest call to my spring controller, it works when I put the URL in browser and able to see the JSON response.我正在尝试对我的 spring 控制器进行休息调用,当我将 URL 放入浏览器并能够看到 JSON 响应时,它会起作用。 But, when I try the same by integrating into the Angular code, it doesn't throw any exception either in browser console or server console.但是,当我通过集成到 Angular 代码中来尝试相同的操作时,它不会在浏览器控制台或服务器控制台中引发任何异常。

Here is my code.这是我的代码。

Imports进口

import { Component, OnInit  } from '@angular/core';
import { Http, Response  } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

class Result {
statusCode : number;
errorMsg: string;
result: string;

}


@Component({
selector: 'app-root',
templateUrl: './app.component.html',
 styleUrls: ['./app.component.css'],

 })
 export class AppComponent {
 ngOnInit() {
   this.getEmployees();
 }

public getEmployees(): Observable<Result[]> {

   return this.http
    .get(this.API_URL + '/employees')
    .map(response => {
     const todos = response.json();
     console.log(todos);
     return "";
})
.catch(this.handleError);
}

private handleError (error: Response | any) {
  console.error('ApiService::handleError', error);
  return Observable.throw(error);
}

And here is my spring code这是我的弹簧代码

  @RequestMapping(value ="/employees", method = RequestMethod.GET)
public ResultDto getEmployees(HttpServletRequest req) {
    ResultDto result = null;
    try {
        ServletContext ctx = req.getServletContext();
        @SuppressWarnings("unchecked")
        Map<String,String> users = (Map<String, String>) ctx.getAttribute("userRoles");
        result = new ResultDto();
        result.setStatusCode(EmapConstants.SUCCESS);
        result.setResult(users);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}

My ResultDto class is having three properties我的 ResultDto 类具有三个属性

private int statusCode;
private String errorMsg;
private Object result;

Any ideas why its not hitting the method?任何想法为什么它没有达到该方法?

Assuming you are using the HttpClient from @angular/common/http :假设您正在使用来自@angular/common/http的 HttpClient :

If you use the HttpClient you can either add a type to the http.get() which is your expected response json.如果您使用 HttpClient,您可以向 http.get() 添加一个类型,这是您预期的响应 json。 Using this you only get the response body as your result.使用它,您只能获得响应正文作为结果。 You could also add the option observe: 'response' to your get request in order to get the actual response back.您还可以将选项observe: 'response'到您的获取请求中,以获取实际响应。

You would probably only want to use the latter if you need other information than the body eg the response status.如果您需要除正文之外的其他信息(例如响应状态),您可能只想使用后者。 If you only need the body your request could look something like this:如果您只需要正文,您的请求可能如下所示:

constructor(private httpClient: HttpClient) {}

getEmployees() Observable<Result[]>{
    return this.httpClient
        .get<Result[]> (this.API_URL + '/employees', {params: _params})
        .pipe(catchError(() => this.handleError()));

}

Yeah and you always have to subscribe to the observable that's right.是的,你总是必须订阅正确的 observable。 As mentioned in the comments as well.正如评论中提到的那样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM