Angular-使用基本身份验证

时间:2018-07-07 03:03:37

标签: angular api http service

我一直在使用angular 6.0.0。我有一个具有基本身份验证的REST API,它在Postman上可以正常工作,但如下所示在我的服务中出现了错误

  

401(未经授权)

这是我的代码:-

import { Injectable } from '@angular/core';
import {Http, Headers} from '@angular/http';
import 'rxjs/add/operator/map';
import { struct_paket } from './data';

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

  constructor(private http: Http) { }
  auth(headers: Headers) {
    headers.append('Authorization', 'Basic ' +
      btoa('admin:310b5678eece63336e4698d2722aad91'));
  }

  getpaket() {
    let headers = new Headers();
    this.auth(headers);

    return  this.http.get('www.example.com/api', {
      headers: headers
    }).map(res => res.json() as struct_paket );


  }
}

更新

service.ts

export class AppserviceService {

constructor(private http: HttpClient) {}

  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json',
      Authorization:
        'Basic YWRtaW46MzEwYjU2NzhlZWNlNjMzMzZlNDY5OGQyNzIyYWFkOTE='
    })
  };
  get() {
    return this.http.get<struct_paket>('http:www.example.com/api', this.httpOptions)
  }
}

并在component.ts中调用它

this._service.get()
    .subscribe(x=>
      {
        this.Pakets = x
      },error =>{console.log(error);}
    );

2 个答案:

答案 0 :(得分:1)

标题现在已移至“ @ angular / common / http”,并且名称也已更改为HttpHeaders。

示例:

4

答案 1 :(得分:1)

追加后

更新标头

尝试

import { Injectable } from '@angular/core';
import {Http, Headers} from '@angular/http';
import 'rxjs/add/operator/map';
import { struct_paket } from './data';

@Injectable({
  providedIn: 'root'
})
export class AppserviceService {
  headers : Headers;
  constructor(private http: Http) { }
  auth() {
    this.headers = this.headers.append('Authorization', 'Basic ' +
      btoa('admin:310b5678eece63336e4698d2722aad91'));
  }

  getpaket() {
    this.headers = new Headers();
    this.auth();

    return  this.http.get('www.example.com/api', {
      headers: headers
    }).map(res => res.json() as struct_paket );


  }
}