如何实现Angular 4或5基本身份验证剩余调用?

时间:2018-10-31 10:24:34

标签: angular angular-httpclient

我正在尝试从无认证的js访问rest服务。它的工作正常。

未经身份验证

getGroupData() {
    this.getUrl = this.coreurlService.serviceURL ;
    const url = this.getUrl.fetchtpaassociations_url+this.localStorageService.get('tpaid')+'' ; 
    return this.http.get(url)
};

具有身份验证

getGroupData(){
    this.getUrl = this.coreurlService.serviceURL ;
    const url = this.getUrl.fetchtpaassociations_url+this.localStorageService.get('tpaid')+'' ; 
    var headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Basic asd239asd9aslkasdASDFASDFSADF9flk34jrlsadkjfLAKSDJFAASLDKJFASLD=='               
        }
    let obs = new Observable(observer => {
        this.http.get(url, {headers: headers}).subscribe(
            (response: Response) => {
                observer.next(response);
                observer.complete();
            },
            error=> {
                observer.error(error);
            });     
    });
    return obs;
};

它不适用于身份验证。请帮助我。 谢谢

1 个答案:

答案 0 :(得分:0)

您是否检查过BasicAuth哈希是否正确?

在确保您的呼叫可以与Rest客户端(例如Postman)正常工作之后,也许您应该尝试使用Angular 4 Headers

getGroupData(){

    this.getUrl = this.coreurlService.serviceURL ;
    const url = this.getUrl.fetchtpaassociations_url+this.localStorageService.get('tpaid')+'' ; 

    let headers: Headers = new Headers();
    let options: RequestOptions = new RequestOptions({ headers: headers });
    options.headers.append('Content-Type', 'application/json');
    options.headers.append('Authorization', 'Basic asd239asd9aslkasdASDFASDFSADF9flk34jrlsadkjfLAKSDJFAASLDKJFASLD==');  

    return this.http.get(url, options);
};

我也直接返回了您的http.get结果,如上例所示。