Angular 2标头和数据 [英] Angular 2 headers and data

查看:56
本文介绍了Angular 2标头和数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Angular 2中,任何人都可以向我展示一个从JSON API提要中获取标头和数据的基本示例吗?我可以看到很多关于如何仅获取数据的示例,但没有看到获取标头的示例.请问您能同时显示组件中的代码,然后再显示服务中的代码吗?

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?

推荐答案

好,标头应位于响应数据中.大多数示例在接收到JSON并订阅映射的流后立即映射JSON.您可以使用RxJS do运算符拦截流并处理原始响应.

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.

服务:

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

组件:

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

这篇关于Angular 2标头和数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆