angular - Angular - 使用基本身份验证获取数据
问题描述
我一直在使用 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 );
}
}
更新
服务.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);}
);
解决方案
追加后更新标题
尝试
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 );
}
}
推荐阅读
- angular - 角度材质单选按钮外圈未对齐
- c - 如何在 C 中重新加载程序?
- python - 在屏幕上移动精灵
- r - 使用spark和R时如何增加内存
- c++ - 从继承的类访问时,成员对象地址似乎发生了变化
- google-bigquery - BigQuery 中对角线元素的总和
- javascript - React - 异步 api 调用,Promise.all 等待调用完成
- python - pandas DataFrame划分的性能非常慢
- firebase - 只有 Android 应用模块可以连接到 Firebase 在线项目
- python - 无法在 Beautifulsoup 中获取所需的文本