httpClient.request(request)和httpClient.post(..)有什么区别

问题描述 投票:0回答:1
export class LoginComponent implements OnInit {
  formValues;

  constructor(private api:ApiService,private http:HttpClient) { }

  ngOnInit() {
  }
  onSubmit(form:NgForm){
    this.formValues = form.value;

    //create new Object
    const x={
      username:this.formValues.username,
      password:this.formValues.password
    }
    console.log(x);
    //request server
    this.api.request('POST','',x).do((data)=>console.log(" server",data))
    .subscribe((data)=>console.log(" server",data.body));
    this.http.post('api/',x).subscribe((data)=>console.log(" this is http.post",data));
  }

}

api.service.ts

 @Injectable()
    export class ApiService {
      private baseUrl=environment.apiUrl;
      constructor(private http:HttpClient) { }


      request(method:string,url:string,body?:Object):Observable<any> {

        url=`${this.baseUrl}/${url}`;

        const httpOptions = {
          headers: new HttpHeaders({
            'Content-Type':  'application/json',
            // 'Authorization': 'my-auth-token'
          })
        };

        const req = new HttpRequest('POST', url, body,httpOptions);
        return this.http.request(req);
      }

    }

服务器端

const express = require('express');
const path = require('path');
function apiRouter(){
    const router = express.Router();
    router.post('',(req,res)=>{
        console.log("api");
        let data= req.body
        console.log(data);
        res.status(200).json({data:"this is data"});
    }); 
    return router;
}
module.exports = apiRouter;

运行应用程序并提交用户名和密码后,我得到了以下结果。

{username: "a", password: "11"}password: "11"username: "a"__proto__: Object
main.b9ea608b60e7f19a98d0.bundle.js:1  server {type: 0}type: 0__proto__: Object
main.b9ea608b60e7f19a98d0.bundle.js:1  server undefined
main.b9ea608b60e7f19a98d0.bundle.js:1  server e {headers: t, status: 200, statusText: "OK", url: "http://localhost:3000/api/", ok: true, …}
main.b9ea608b60e7f19a98d0.bundle.js:1  server {data: "this is data"}
main.b9ea608b60e7f19a98d0.bundle.js:1  this is http.post {data: "this is data"}

当我按可观察的顺序执行httpClient.request()时,有两个事件。第一个是{type:0},第二个是e {headers:t,status:200,statusText:“ OK”,url:“ http://localhost:3000/api/”,ok:true,…}。但在httpClient.post()中只有{data:“这是数据”}}。

我有两个问题:1. httpClient.request()和httpClient.post()有什么区别2.在httpClient.request()中为什么返回{type:0}?

angular httpresponse
1个回答
0
投票
© www.soinside.com 2019 - 2024. All rights reserved.