Angular的HTTP请求

1.在总的项目app.module.css中导入HTTP用的到module
	import { HttpClientModule} from "@angular/common/http"		
	//之后再Imports中注册
	@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...
    HttpClientModule
  ],
  ...
})

2.在我们要用到该服务的组件的ts文件中加入该module以及RouterModule
	import { HttpClient } from "@angular/common/http" //这里是HttpClient
	import { Router } from "@angular/router"
3.在方法中发送post请求
	//组件的构造方法中加入服务
	constructor(
    	private http: HttpClient,
    	private router: Router
    	) { }  
  	//钩子函数
  	ngOnInit() {
  	}
	//用于接收表单提交的数据
 	 signupForm={
    	email: '',
    	password: ''
  	}
	//用于接收返回的错误信息
  	email_err_msg=''

 	 public signup(){
    // 1. 表单验证--好像不是前端验证?
    // 2. 获取表单数据
    const formData=this.signupForm;  
    // 3. 发起 http 请求和服务端交互
    this.http.post('http://localhost:3000/users',formData)
    .toPromise()
    .then((data: any)=>{
      console.log(data)
      // 4. 根据响应结果做交互处理
      this.email_err_msg='';
        //将token和返回的用户信息存储到本地
      window.localStorage.setItem('auth_token',data.token);
      window.localStorage.setItem('user_info',JSON.stringify(data.user));
        //定向到list展示页面
      this.router.navigate(['/']);
    })
    .catch(err=>{
        //数据进行序偶无信息处理
      if(err.status===409){
        this.email_err_msg='邮箱已经注册'
      }
    })
  }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值