Http post请求角度2到ReST API

时间:2017-11-21 07:04:42

标签: angular spring-boot

我正在尝试使用创建的Rest API在角度2中实现get和post请求。

我能够成功实现get请求并从我的API中获取数据。

但我无法提出要求。

下面显示的是我的Rest微服务代码

@CrossOrigin(origins = "http://localhost:4200")
@GetMapping("/checkUsers")
public String checkLogin() throws JsonProcessingException {

    ObjectMapper mapper = new ObjectMapper();
    List<Users> useObj = (List<Users>) userRepo.findAll();
    return(mapper.writeValueAsString(useObj));
}

@CrossOrigin(origins = "http://localhost:4200")
@RequestMapping(value = "/checkByCredential", method = RequestMethod.POST)
public String checkLoginByName(@RequestBody Users user) throws Exception{

    ObjectMapper mapper = new ObjectMapper();
    Users useObj1 = 
userRepo.findByUsernameAndPassword(user.username,user.password);
    return(mapper.writeValueAsString(useObj1));
}

下面显示的是我的角度2代码片段

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { HttpModule } from '@angular/http';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { BasicService } from './basic.service';


@NgModule({

  declarations  : [AppComponent ],
  imports       : [BrowserModule,HttpModule,FormsModule ],
  providers     : [BasicService],
  bootstrap     : [LoginpostComponent]

})

export class AppModule { }

app.component.ts

import { Component } from '@angular/core';
import { BasicService } from './basic.service';

@Component({
  selector: 'app-root',
  template: `<h1>{{ title }}</h1>
            <div style="height: 200px; overflow: auto;"> 
             <table *ngFor= " let item of data">
                 <tr><td>Username</td><td>{{ item.username }}</td></tr>
                 <tr><td>Password</td><td>{{ item.password }}</td></tr>
             </table>
            </div>`

})
export class AppComponent {
  title :string;
  data:any;

  constructor(private MyService: BasicService){
        this.title="Angular Service";

        this.MyService.GetUsers()
        .subscribe(users => {this.data = users });
  }
}

basic.service.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class BasicService {

  constructor(private http:Http) { }

    GetUsers(){
            return this.http.get('http://localhost:8080/checkUsers')
            .map(result => result.json());
    }


}

任何人都可以指导如何使用我的ReSTAPI实现发布请求,这样当我提交表单数据时,它应该从我的API验证凭据

1 个答案:

答案 0 :(得分:1)

Angular 2+中的POST调用可以与您已有的GetUsers()调用方式类似:

checkByCredential(username: string, password: string) {
  const user = { username: username, password: password };
  return this.http
    .post('http://localhost:8080/checkByCredential', user) // Just add the second argument
    .map(result => result.json());
}

user对象应该与Users类(控制器中的@RequestBody参数)具有相同的结构。你甚至可以为它创建一个TypeScript接口。

此外,您不需要mapper.writeValueAsString(useObj),Spring启动会为您执行此操作,因此您可以将Java代码重构为:

@CrossOrigin(origins = "http://localhost:4200")
@GetMapping("/checkUsers")
public List<Users> checkLogin() throws JsonProcessingException {
    return (List<Users>) userRepo.findAll();
}

@CrossOrigin(origins = "http://localhost:4200")
@RequestMapping(value = "/checkByCredential", method = RequestMethod.POST)
public Users checkLoginByName(@RequestBody Users user) throws Exception{
    return userRepo.findByUsernameAndPassword(user.username,user.password);
}