我正在尝试使用创建的Rest API在角度2中实现post请求。
我的表单未加载,我无法向我的API发送请求。
我在控制台中收到此错误
@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));
}
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 : [AppComponent ]
})
export class AppModule { }
import { Component } from '@angular/core';
import { BasicService } from './basic.service';
@Component({
selector: 'app-root',
template: `<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)="checkByCredential(username,password)">Login</button>
</form>`
})
export class AppComponent {
title :string;
data:any;
constructor(private MyService: BasicService){
this.title="Angular Service";
checkByCredential(username: string, password: string) {
this.MyService.checkByCredential(username, password).subscribe(users => this.data = users);
}
}
}
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class BasicService {
constructor(private http:Http) { }
checkByCredential(username: string, password: string) {
const user = { username: username, password: password };
const headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http
.post('http://localhost:8080/checkByCredential', user, { headers: headers })
.map(result => result.json())
}
}
}
任何人都可以指导如何使用我的ReSTAPI实现发布请求,这样当我提交表单数据时,它应该从我的API验证凭据
答案 0 :(得分:1)
您的AppComponent
课程存在问题。使用以下AppComponent
类:
export class AppComponent {
title: string;
data: any;
constructor(private MyService: BasicService){
this.title="Angular Service";
}
checkByCredential(username: string, password: string) {
this.MyService.checkByCredential(username, password).subscribe(users => this.data = users);
}
}