Reputation: 3092
In Angular 2, please can anyone show me a basic example of getting both the headers and data from a JSON api feed? I can see lots of examples on how to get the data only but no examples to get the headers. Please could you show me both the code in the component and then the code in the service?
Upvotes: 2
Views: 388
Reputation: 1982
Well, the headers should be in the response data. Most of the examples map the JSON immediately after receiving it and subscribing to the mapped stream. You can use RxJS do
operator to intercept the stream and work with raw response.
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
@Injectable()
export class UserService {
constructor(http:Http) {
this.people = http.get('https://jsonplaceholder.typicode.com/users')
.do((data) => {
console.log(data.headers);
// do your magic here
})
.map(res => res.json());
}
}
If you want to manipulate the data differently on each emitted value of the stream, it would be best if you avoid mapping before you can read the data.
Service:
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
@Injectable()
export class UserService {
constructor(http:Http) {
}
getUsers() {
return this.http.get('https://jsonplaceholder.typicode.com/users');
}
}
Component:
export class UserComponent implements OnInit {
users: any[];
constructor(private userService: UserService) { }
getUsers(): void {
this.userService.getUsers().subscribe(result => {
let headers = result.headers;
this.users = result.json();
// rest of the magic
});
}
ngOnInit(): void {
this.getUsers();
}
}
Upvotes: 5
Reputation: 2138
Heres is the code for setting headers!
import { Injectable } from '@angular/core';
import { Http, Response, RequestOptionsArgs, Headers } from '@angular/http';
@Injectable()
export class AzureService {
headers: Headers;
constructor(private http: Http) {
this.headers = new Headers();
this.headers.append('Content-Type', 'application/json');
this.headers.append('ZUMO-API-VERSION', '2.0.0');
}
getUsers(){
http.get(<URL>,this.headers)
.do((data) => {
})
.map(res => res.json());
}
And for getting Headers from API, you can refer to @Adnan A. answer!
Upvotes: 2