具有基本Authorizartion的角度Api请求

时间:2017-12-02 18:28:31

标签: angular get basic-authentication

我如何在 Angular Framework 中创建此Jquery请求?我是一个非常新的角形框架,但我爱它。我喜欢弄清楚如何使用基本授权标头创建HTTP Get。

var settings = {
  "url": "https://sampleapi.com",
  "method": "GET",
  "headers": {
    "authorization": "Basic QjNYRnZ6S1Jk",
    "content-type": "aplication/json"
  }
}

$.ajax(settings).done(function (response) {
  console.log(response);
});

我应该构建一个服务控制器还是只构建一个常规组件。

3 个答案:

答案 0 :(得分:0)

您可以使用 RequestOptions ,如下所示

const url = `https://sampleapi.com`;
const headers = new Headers();
headers.append('Authorization', 'Basic QjNYRnZ6S1Jk');
headers.append('Content-Type', 'application/json');
const options = new RequestOptions({ headers: headers });
return this.http.get(url, options)
    .map(this.extractData)
    .catch(this.handleErrors);

private extractData(res: Response) {
            const data = res.json();
            return data;
}

private handleErrors(error: Response | any) {
    let errMsg: string;
    if (error instanceof Response) {
        const body = error.json() || '';
        const err = body.error || JSON.stringify(body);
        errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
        errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg);
}

答案 1 :(得分:0)

如果您使用的是Angular 4.3及更高版本,并希望使用新的HttpClient和HttpHeaders,那么这可能对您有用。

以下是使用基本授权进行通话的服务:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

const url = `https://sampleapi.com`;

@Injectable()
export class BasicService {
  private _headers = new HttpHeaders().set('Content-Type', 'application/json');
  constructor(private httpClient: HttpClient) { }

  getWithBasicAuth(): Observable<any> {
    const headers = this._headers.append('Authorization', 'Basic QjNYRnZ6S1Jk');
    return this.httpClient.get<any>(url, { headers : headers });
  }
}

这是一个将使用上述服务的组件。

import { Component, OnInit } from '@angular/core';
import { BasicService } from '../services/basic.service';

@Component({
  selector: 'app-basic',
  templateUrl: './basic.component.html',
  styleUrls: ['./basic.component.css']
})
export class BasicComponent implements OnInit {
  dataFormService: any;

  constructor(private basicService: BasicService) { }

  ngOnInit() {
    this.basicService.getWithBasicAuth().subscribe(data => this.dataFormService = data);
  }
}

您可能希望将服务的返回类型从any更改为更合适的内容。

答案 2 :(得分:0)

Angular 4 + 如果你想编码清洁结构良好的程序

  1. 首先,您必须创建如下代码的服务:

    // Class name is setting.service.ts
    
    import {Injectable} from '@angular/core';
    import {HttpClient} from '@angular/common/http';
    import {HttpHeaders} from '@angular/common/http';
    
    @Injectable()
    export class SettingService {
        constructor(public http: HttpClient, public url: string) { }
    
        get() {
            let headers = new HttpHeaders();
            headers.set('authorization', 'Basic QjNYRnZ6S1Jk');
            headers.set('content-type', 'application/json');
    
            return this.http.get(this.url}, {headers: headers});
        }
    }
    
  2. 然后在 app.module.ts 中使用此服务,在导入内放置 HttpClientModule 并在提供商<内/ strong>提供您的服务(此处为 SettingService ):

    import {BrowserModule} from '@angular/platform-browser';
    import {NgModule} from '@angular/core';
    import {HttpClientModule} from '@angular/common/http';
    
    import {SettingService} from './services/setting.service';
    
    @NgModule({
        declarations: [
            AppComponent
        ],
        imports: [
            BrowserModule,
            HttpClientModule
        ],
        providers: [
            SettingService
        ],
        bootstrap: [AppComponent]
    })
    export class AppModule {
    }
    
  3. 毕竟,您可以使用以下代码中的服务:

    // Class name is home.component.ts
    
    import {Component} from '@angular/core';
    
    import {SettingService} from './services/setting.service';
    
    @Component({
        selector: 'app-home',
        templateUrl: './home.component.html',
        styleUrls: ['./home.component.css']
    })
    export class HomeComponent {
    
        constructor(private settingService: SettingService) {
            this.settingService.get('https://sampleapi.com').subscribe(
                (success) => {               
                    console.log(success);
                },
                (error) => {
                    console.log(error);
                },
                () => {
                    console.log('Complete')
                }
             );
        }
    }
    
  4.   

    注意:我将请求放在构造函数中,但您可以将其放入   到处