如何在angular2中发布帖子请求?

时间:2017-11-20 15:08:45

标签: 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 { LoginpostComponent } from './loginpost.component';
import { BasicService } from './basic.service';


@NgModule({

  declarations  : [AppComponent, LoginpostComponent ],
  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());
    }


}

loginpost.component.ts

import { Component } from '@angular/core';
import { Http, Headers } from '@angular/http';

@Component({
  selector: 'app',
  template:`<app-root></app-root>   
                    <h2>Login</h2>
                      <form role="form">
                           <div ng-control-group="credentials">
                            <label for="username">Username</label>
                             <input
                                  type="text"
                                  #username
                                  id="username"
                                  ng-control="username"
                                  required>

                            <label for="password">Password</label>
                             <input
                                  type="password"
                                  #password
                                  id="password"
                                  ng-control="password"
                                  required>
                           </div>
                                <button (click)="authenticate(username, password)">Login!</button>

                        </form>`
})


export class LoginpostComponent {
  title: string;
  data: string;
  username: string;
  password: string;


  constructor(public http: Http) { }


  authenticate(username, password) {

    let creds = JSON.stringify({ username: username.value, password: password.value });

    let headers = new Headers();
    headers.append('Content-Type', 'application/json');

    this.http.post('http://localhost:8080/checkByCredential', creds, {headers: headers})
      .subscribe(data => {         
          username.value = '';
          password.value = '';
        },
        () => console.log()
      );
  }

}
;

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

0 个答案:

没有答案