Angular 2 observable如何提取响应?

时间:2016-11-22 22:25:48

标签: angular rxjs angular2-observables

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})我未定义。我怎么得到并返回this.data ??

显然,如果我写了另外一个返回,如下所示,observable还没有完成,所以它将返回空数据:any。

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

1 个答案:

答案 0 :(得分:4)

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

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

  

Angular AsyncPipe是一个不纯的管道的一个有趣的例子。 AsyncPipe接受Promise或Observable作为输入并自动订阅输入,最终返回发出的值。

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>