1.在总的项目app.module.css中导入HTTP用的到module
import { HttpClientModule} from "@angular/common/http"
@NgModule({
declarations: [
...
],
imports: [
...
HttpClientModule
],
...
})
2.在我们要用到该服务的组件的ts文件中加入该module以及RouterModule
import { HttpClient } from "@angular/common/http"
import { Router } from "@angular/router"
3.在方法中发送post请求
constructor(
private http: HttpClient,
private router: Router
) { }
ngOnInit() {
}
signupForm={
email: '',
password: ''
}
email_err_msg=''
public signup(){
const formData=this.signupForm;
this.http.post('http://localhost:3000/users',formData)
.toPromise()
.then((data: any)=>{
console.log(data)
this.email_err_msg='';
window.localStorage.setItem('auth_token',data.token);
window.localStorage.setItem('user_info',JSON.stringify(data.user));
this.router.navigate(['/']);
})
.catch(err=>{
if(err.status===409){
this.email_err_msg='邮箱已经注册'
}
})
}