角度Api请求与基本Authorizartion

我如何使这个jquery请求在角框架?我非常喜欢角度框架,但我很喜欢它。我喜欢弄清楚如何使用基本授权标题进行HTTP获取。角度Api请求与基本Authorizartion

var settings = { 

"url": "https://sampleapi.com",

"method": "GET",

"headers": {

"authorization": "Basic QjNYRnZ6S1Jk",

"content-type": "aplication/json"

}

}

$.ajax(settings).done(function (response) {

console.log(response);

});

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

回答:

您可以使用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);

}

回答:

这里是有可能为你工作,如果你使用的是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改变从服务的返回类型更合适一些。

回答:

在角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和内部提供商把你的服务(这里是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')

    }

    );

    }

    }

注意:我pu牛逼我的要求内构造但你可以把它 到处

以上是 角度Api请求与基本Authorizartion 的全部内容, 来源链接: utcz.com/qa/257678.html

回到顶部