Angular 2 observable 如何提取响应?

Angular 2 observable How do I extract response?

import { Injectable }     from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Rx';

// Import RxJs required methods
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch'

@Injectable()
export class EquipmentService{
    data: any;
    constructor(private http:Http){

    }
    getDefaultEquipment(){
        this.http.get('./app/SaveData/equipmentTest.json')
            .map((res:Response) => res.json())
            .subscribe(data => { this.data = data},
                err => console.error(err),
                () => console.log(this.data));
    }
}

从文件中读取数据,重要的一点是getDefaultEquipment()

如果你看到最后的console.log(this.data)数据是正确的,这正是我所需要的。但是如果我 return this.http.get(... () => {return this.data}) 我得到未定义。我如何到达 return this.data??

显然,如果我写另一个 return 如下所示,observable 还没有完成,所以它将 return 空数据:任何。

//clearly won't work because the get hasn't returned yet
getDefaultEquipment(){
    this.http.get(...data => {this.data = data}...);
    return this.data;
}

以下是我的看法。未经测试,但这个概念是可靠的。这将为您节省大量样板代码,因为 async 管道基本上吃掉了 Observables。如果您需要进行一些转换,那么在返回可观察对象之前也可以这样做。您可以在服务中执行此操作,也可以在组件中执行此操作。请记住有关 Observables 的事情,如果您有多个订阅者,请务必使用 .share() 运算符,否则您将为每个订阅者执行一次(在这种情况下)http.get.do 运算符也是如此,它可以派上用场,但也像订阅者一样。

我建议阅读 RxJs 并查看 angulars 网站上有关异步管道用法的示例。

The Angular AsyncPipe is an interesting example of an impure pipe. The AsyncPipe accepts a Promise or Observable as input and subscribes to the input automatically, eventually returning the emitted value(s).

equipment.service.ts

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Rx';

export interface Equipment {
  name: string;
  id: string;
}

@Injectable()
export class EquipmentService {

  constructor(private http:Http){}

  public getDefaultEquipment(): Observable<Equipment[]> {
    return this.http
    .get('./app/SaveData/equipmentTest.json')
    .map((res:Response) => res.json());
  }
}

装备-list.component.ts

import { Component, OnInit } from "@angular/core";
import { EquipmentService, Equipment } from "./services/equipment.service";
import { Observable } from 'rxjs/Rx';

@Component({
  selector: 'equipment-list',
  templateUrl: './equipment-list.component.html',
  styleUrls: ['./equipment-list.component.css'],
  providers:[
     EquipmentService
  ]
})
export default class EquipmentComponent {

    constructor(private service: EquipmentService) {}

    public get equipment():Observable<Equipment[]> {
        return this.service.getDefaultEquipment();
    }
}

装备-list.component.html

<ul>
    <li *ngFor="item of (equipment | async)>
       <span>{{item.id}}</span>
       <span>{{item.name}}
    </li>
</ul>