带有标题的HttpClientModule http帖子不起作用

时间:2019-02-19 12:01:30

标签: typescript angular6

我无法使用有角度的httpclientmodule从服务器获得响应, 我对angular6 httpclientmodule完全陌生,请找到以下代码

myservice.ts

import { Injectable } from '@angular/core';
import {Observable} from "rxjs/Observable";
import {HttpClient, HttpHeaders} from "@angular/common/http";
import { map } from 'rxjs/operators';
import { Headers, RequestOptions } from '@angular/http';
import 'rxjs/Rx';

@Injectable({
  providedIn: 'root'
})
export class MyserviceService {

  response: any;
  constructor(private http: HttpClient) { }


 getLogin(mobileNumber, loginPassword) {
  let headers= new HttpHeaders().set('Content-Type','application/json').set('X-Authorization','clientmobileClient1').set('username',mobileNumber).set('password',loginPassword);
    return this.http.post('http://My API URL', null, {headers}).map((response: any) => response.json());

  }
}

mycomponent.ts

 onSubmit() {
    this.service.getLogin(mobileNumber, loginPassword).subscribe((response: any) => { console.log("my response", response) });
}

请帮助我解决我的问题。

谢谢

2 个答案:

答案 0 :(得分:2)

尝试一下:

let Params = new HttpParams();
    Params = Params.append('username', mobileNumber);
    Params = Params.append('password', loginPassword);
const header = new HttpHeaders({ 'Content-Type': 'application/json','X- 
    Authorization':'clientmobileClient1' });
    var options = { headers: header, params: Params };
    return this.http.post('http://My API URL', {}, options);

答案 1 :(得分:1)

我个人使用HTTP_INTERCEPTORS将标头添加到HTTP请求中。这是我为请求设置标题的方式。我注意到您发送的是usernamepassword,这不是最佳做法。

这就是我会怎么做的

getLogin(mobileNumber, loginPassword) {
  const headers = new HttpHeaders()
    .set('Content-Type','application/json')
    .set('X-Authorization','clientmobileClient1')
    .set('username',mobileNumber)
    .set('password',loginPassword);
  return this.http.post<any>(
    'http:://url.api',
    {}, // Because its a post request
    { headers: headers }
  ).pipe(map(response => {
    return response;
  }))
}

但是我宁愿将其作为这样的获取请求

getLogin(mobileNumber, loginPassword) {
  const headers = new HttpHeaders()
    .set('Content-Type','application/json')
    .set('X-Authorization','clientmobileClient1')
    .set('username',mobileNumber)
    .set('password',loginPassword);
  return this.http.get<any>(
    'http:://url.api',
    { headers: headers }
  ).pipe(map(response => {
    return response;
  }))
}

但是我宁愿这样,在请求正文中发送敏感数据。像下面但这全取决于您如何编写API。

getLogin(mobileNumber, loginPassword) {
  const headers = new HttpHeaders()
    .set('Content-Type','application/json')
    .set('X-Authorization','clientmobileClient1');
  return this.http.post<any>(
    'http:://url.api',
    {
      mobileNumber,
      loginPassword
    },
    { headers: headers }
  ).pipe(map(response => {
    return response;
  }))
}

如果需要,我可以包含设置HTTP_INTERCEPTORS

的代码