Angular 6:如何将用户名和密码传递给API?

时间:2019-02-24 03:34:24

标签: angular

请帮助。我只是不明白这一点-我有一个API,我要从中索取房屋清单,但无法将用户名和密码传递给(获得未经授权的访问返回)。我通过这些信息的各种尝试都陷入僵局。

我的具体问题是:如何以及在哪里传递用户名和密码(在getHomes()中?)?

谢谢。

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { map, catchError, tap } from 'rxjs/operators';

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

  constructor(private http: HttpClient) { }

  auth = ('user:password');
  endpoint = 'https://api.com';
  httpOptions = {
  headers: new HttpHeaders({
    'Authorization': 'Basic' + btoa(this.auth),
    'Content-Type':  'application/json'
  })
};

private extractData(res: Response) {
  let body = res;
  return body || { };
}

getHomes(): Observable<any> {
  return this.http.get(this.endpoint + 'houses').pipe(
    map(this.extractData));
}

2 个答案:

答案 0 :(得分:0)

首先,您的RestService代码存在一些奇怪的问题,将httpOptions分配挂在中间。可能您需要放置在构造函数中或getHomes方法中。 然后,您可以按以下方式传递httpOptions

http.get method this.http.get(this.endpoint + '/houses',httpOptions) //assign it here

答案 1 :(得分:0)

在类中将标头声明为any

headers:any;

在构造函数中分配标头的值:

  constructor(private http: HttpClient) { 
    this.headers = new HttpHeaders({      
      'Content-Type': 'application/json',
      'Content-Encoding': 'none',
      'Authorization': 'Basic' + btoa(this.auth)
    });
}

并通过以下方式将标头传递至get方法:

this.http.get(this.endpoint + '/houses', {headers:this.headers})