2017-12-02 253 views
-1

我如何使這個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); 
}); 

我應該建立一個服務控制器還是一個常規組件。

+1

如果你愛上了這個框架是這樣,你爲什麼不以涵蓋HTTP相關的問題一個基本的教程? (有很多) –

+1

或者也許只是谷歌周圍:https://angular.io/guide/http(角度http請求的第一個結果) –

回答

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); 
} 
0

這裏是有可能爲你工作,如果你使用的是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改變從服務的返回類型更合適一些。

0

角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牛逼我的要求內構造但你可以把它 到處

+0

錯誤在src/app/setting.service.ts(14,38 ):錯誤TS1005:','預計。 src/app/setting.service.ts(14,39):錯誤TS1068:意外的標記。期望構造函數,方法,訪問器或屬性 。 src/app/setting.service。ts(14,41):錯誤TS1068:意外的標記。期望構造函數,方法,訪問器或屬性 。 src/app/setting.service.ts(14,59):錯誤TS1128:聲明或預期的語句。 src/app/setting.service.ts(15,5):錯誤TS1128:聲明或預期的語句。 src/app/setting.service.ts(16,1):錯誤TS1128:預期的聲明或語句。 –

+0

爲什麼我做錯了或沒做?大聲笑 –

+0

請注意組件和服務中的typescript路徑,例如我把我的服務放在service文件夾裏面 –