Angular 5调用Spring Restful Controller

时间:2018-02-11 17:45:30

标签: typescript angular5 spring-restcontroller

  1. 我正在使用Spring启动并拥有以下Restful Controller。它的工作正常,我用PostMan进行了测试。

    @RestController
    public class AuthController {
    
    @Autowired
    private UserRepository userRepository;  
    
    @PostMapping("/login")
    public User login(@RequestBody User user) {
        User currentUser = userRepository.findOneByUserIdAndPassword(user.getUserId(), user.getPassword());
        System.out.println("currentUser : "+currentUser);
        return (currentUser == null ? new User() : currentUser);
    }
    }
    
  2. Angular 5 Credentials对象:

    export class Credentials {
    
    userId: string;
    password: string;
    
    constructor(userId: string, password: string) {
        this.userId = userId;
        this.password = password;
    }
    }
    
  3. Angular 5组件:login.component.ts

    login(): void {
    
       //Looking to do something like this.
       User user = this.authService.login(this.credentials);
       if(user.userId === '') {
         this.isLoggedIn = false;
       } else {
         this.isLoggedIn = false;
       }
    }
    
  4. Angular 5服务:auth.service.ts

  5. 尝试使用此功能。

    login(credentials : Credentials): Promise<User> {
    return this.http
      .post(API_URL + '/login', JSON.stringify(credentials), httpOptions)
      .toPromise()
      .then(() => User)
      .catch(this.handleError);
    
      } 
    

    但我在通话中收到此错误。呼叫也没有到达服务器。

    core.js:1448 ERROR Error: Uncaught (in promise): Object: {"body":{"error":"Collection 'undefined' not found"},"url":"http://localhost:8080/login","headers":{"normalizedNames":{},"lazyUpdate":null},"status":404,"statusText":"Not Found"}
        at resolvePromise (zone.js:809)
        at resolvePromise (zone.js:775)
    

    我也尝试使用但无法接听电话。

    login(credentials : Credentials): Observable<Credentials> {
        return this.http.post<Credentials>(API_URL + '/login', credentials, httpOptions);
    }
    

    欣赏任何指示。

1 个答案:

答案 0 :(得分:0)

您的最新尝试看起来很严重,但您需要订阅您的登录功能,如果您不这样做,则永远不会触发该呼叫。在订阅功能中,您可以使用该服务提供的凭据。有关详细信息,请参阅https://angular.io/guide/http

this.authService.login(this.credentials).subscribe((user) => {
   if(user.userId === '') {
     this.isLoggedIn = false;
   } else {
     // probably a copy+paste issue to set it to false?
     this.isLoggedIn = false;
   }
}