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

Reading data from a file, The important bit is getDefaultEquipment().

If you see the last console.log(this.data) the data is correct, it's exactly what I need. But if I return this.http.get(... () => {return this.data}) i get undefined. How do I get at and return this.data??

Obviously if I write another return such as the following, the observable hasn't completed yet, so it will return the empty data: any.

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

1 回答 1

4

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

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

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

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

设备列表.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>
于 2016-11-22T22:36:32.890 回答