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

最佳答案

好吧,标题应该在响应数据中。大多数示例在接收到JSON并订阅映射的流后立即映射JSON。您可以使用RxJS do运算符来拦截流并使用原始响应。

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

如果要在流的每个发射值上对数据进行不同的处理,最好在读取数据之前避免映射。

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

关于javascript - Angular 2 header 和数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42473434/

10-12 00:32
查看更多