2017-05-31 60 views
5

我向API發送請求,它會返回一個數據數組,但我不知道如何從該URL中提取頭文件,這是我嘗試過的我的服務Angular 4從API響應中獲取頭文件

@Injectable() 
export class ResourcesService { 
private resourcesurl = "http://localhost:9111/v1/resources"; 

constructor(private http: Http) { } 

getResources() { 
    let headers = new Headers(); 
    headers.append("api_key", "123456"); 
    return this.http.get(this.resourcesurl, { headers: headers 
}).map(this.extractData).catch(this.handleError); 
} 
getresourceheaders(){ 
    let headers = new Headers(); 
    headers.append("api_key", "123456"); 
    let options = new RequestOptions(); 
    let testsss = options.headers 
    let headerapi = this.http.request(this.resourcesurl, options); 
    let test = this.http.get(this.resourcesurl, { headers: headers }); 
    console.log(headerapi); 
} 
private extractData(res: Response) { 
    let body = res.json(); 
    return body.data || {}; 
} 
private handleError(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); 
} 
} 

我想從響應,在這種情況下是resourceurl

任何想法得到了頭?

回答

9

的標題是Response class的一部分,所以你應該能夠看到他們在處理類似

http.get('/path/to/resource') 
    .subscribe((res:Response) => { 
    console.log(res.headers); 
    // you can assign the value to any variable here 
    }); 
+0

that worked !,但現在,我該如何獲得該值?我想將它傳遞給一個變量,我試圖在函數內部和外部聲明它,但它不起作用 – Lrawls

+0

你的服務應該返回http。get('/ path/to/resource')部分,以便您可以處理需要該服務的組件中的訂閱。我更新了語法,以便箭頭函數可以在預訂處理程序 – ruedamanuel

0

角Http.get方法的返回值類型返回響應類型。該對象具有包含關於標題的信息的標題對象。它也有一個url屬性。

this.http.get(url).map(resp => console.log(resp)); 
5

當你做.map(this.extractData)let body = res.json()this.extractData功能從除body響應拿出一切。

取而代之,如果您執行以下操作,.map((res: Response) => res)將返回整個響應,您可以訪問所有屬性並將它們分配給變量。

這是一個Plunker demo

+0

中運行多行,ty! – Lrawls

+0

很高興它工作:) – Nehal

+0

迄今爲止提供的最好的例子。謝謝 –

1

在下面顯示的Angular 5中有一個奇特的例子。使用HttpClient發佈到GraphQL服務器,讀取響應,然後提取響應標頭值和響應正文值。在這種情況下,標題爲Total-Count汽車是在體內的另一個字段數據的字段(汽車陣列)。還示出了使用rxjs 第一個算子而不是訂閱

import { HttpClient, HttpHeaders, HttpResponse } from '@angular/common/http'; 
import { first } from 'rxjs/operators/first'; 
import { Car, CarPage } from '../models/car'; 
.......... 
.......... 

public find(filter: string, sort: string, limit: number): Observable<CarPage> { 
    let headers = new HttpHeaders().set("Content-Type", "application/graphql"); 
    let carPage: CarPage = { cars: [], totalCount: 0 }; 
    return this.http.post<HttpResponse<any>>('/graphql', 
    `query cars { cars(filter: "${filter}", sort: "${sort}", limit: ${limit}) { 
      id 
      make 
      model 
      year 
     } 
     }`, 
     { headers: headers, observe: "response" } 
) 
    .first((_, index) => index === 0, (response: HttpResponse<any>) => { 
    let totalCountHeaderValues = response.headers.getAll("Total-Count"); 
    carPage.totalCount = (totalCountHeaderValues.length > 0) ? parseInt(totalCountHeaderValues[0]) : 0; 
    carPage.cars = response.body.data.cars; 
    return carPage; 
    }) 
} 
1

清除角5回答

默認情況下,this.http.whatever所返回觀察到的將是對數據返回,而不是HttpResponse對象。

如果您的峯值位於:https://angular.io/api/common/http/HttpClient 您會注意到這些選項採用「observe」參數。雖然它沒有記錄什麼的選項,如果你把它作爲「迴應」,那麼你反而會收到HttpResponse<T>https://angular.io/api/common/http/HttpResponse

這樣一個實例,這裏是一個例子請求:

this.http.get(url, {observe: 'response}) 
    .subscribe(resp => console.log(resp.headers)) 

注意:由於瀏覽器cors的安全性,除非API提供Access-Control-Expose-Headers:與您的自定義標題,否則您將無法看到標題,如果您的api和角度應用程序不具有相同的域。