Angular 2 サービスから Observable を作成して返す 質問する

Angular 2 サービスから Observable を作成して返す 質問する

これはむしろ「ベスト プラクティス」に関する質問です。 、 、 の 3 つのプレーヤーがあります。ComponentServiceModel呼び出しComponentServiceデータベースからデータを取得します。 はService次を使用します。

this.people = http.get('api/people.json').map(res => res.json());

を返しますObservable

は、Componentを購読するだけで済みますObservable:

    peopleService.people
        .subscribe(people => this.people = people);
      }

しかし、私が本当に望んでいるのは、 がデータベースから取得したデータから作成されたオブジェクトServiceを返すことです。 はsubscribe メソッドでこの配列を作成できることに気づきましたが、サービスがそれを実行して で利用できるようにした方がきれいだと思います。Array of ModelServiceComponentComponent

その配列を含むService新しい を作成してそれを返すにはどうすればよいでしょうか?Observable

ベストアンサー1

更新: 2016 年 9 月 24 日 Angular 2.0 安定版

この質問には依然として多くのアクセスがあるため、更新したいと考えました。アルファ、ベータ、および 7 つの RC 候補からの変更が激しかったため、安定するまで SO の回答の更新を停止しました。

これは、科目そしてリプレイ主題

個人的にReplaySubject(1)遅れて新しいサブスクライバーが接続した場合でも、最後に保存された値を渡すことができるため、使用することをお勧めします。

let project = new ReplaySubject(1);

//subscribe
project.subscribe(result => console.log('Subscription Streaming:', result));

http.get('path/to/whatever/projects/1234').subscribe(result => {
    //push onto subject
    project.next(result));

    //add delayed subscription AFTER loaded
    setTimeout(()=> project.subscribe(result => console.log('Delayed Stream:', result)), 3000);
});

//Output
//Subscription Streaming: 1234
//*After load and delay*
//Delayed Stream: 1234

そのため、遅れてアタッチしたり、後でロードする必要がある場合でも、常に最新の呼び出しを取得でき、コールバックを見逃す心配はありません。

これにより、同じストリームを使用して次の場所にプッシュダウンすることもできます。

project.next(5678);
//output
//Subscription Streaming: 5678

しかし、100%確信していて、呼び出しを1回だけ行う必要がある場合はどうでしょうか?主題と観測可能なものをオープンにしておくのは良くありませんが、常に"もしも?"

そこで非同期件名入って来る。

let project = new AsyncSubject();

//subscribe
project.subscribe(result => console.log('Subscription Streaming:', result),
                  err => console.log(err),
                  () => console.log('Completed'));

http.get('path/to/whatever/projects/1234').subscribe(result => {
    //push onto subject and complete
    project.next(result));
    project.complete();

    //add a subscription even though completed
    setTimeout(() => project.subscribe(project => console.log('Delayed Sub:', project)), 2000);
});

//Output
//Subscription Streaming: 1234
//Completed
//*After delay and completed*
//Delayed Sub: 1234

素晴らしい! 件名を閉じたにもかかわらず、最後に読み込んだ内容で返信が返ってきました。

もう 1 つは、その http 呼び出しをサブスクライブして応答を処理する方法です。地図応答を処理するのに最適です。

public call = http.get(whatever).map(res => res.json())

しかし、これらの呼び出しをネストする必要がある場合はどうでしょうか? はい、特別な機能を持つサブジェクトを使用できます:

getThing() {
    resultSubject = new ReplaySubject(1);

    http.get('path').subscribe(result1 => {
        http.get('other/path/' + result1).get.subscribe(response2 => {
            http.get('another/' + response2).subscribe(res3 => resultSubject.next(res3))
        })
    })
    return resultSubject;
}
var myThing = getThing();

しかし、これは多すぎるので、それを実行するには関数が必要です。フラットマップ:

var myThing = http.get('path').flatMap(result1 => 
                    http.get('other/' + result1).flatMap(response2 => 
                        http.get('another/' + response2)));

素晴らしいですね。これは、var最終的な http 呼び出しからデータを取得する observable です。

それは素晴らしいですが、Angular2 サービスが欲しいです。

見つけた:

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { ReplaySubject } from 'rxjs';

@Injectable()
export class ProjectService {

  public activeProject:ReplaySubject<any> = new ReplaySubject(1);

  constructor(private http: Http) {}

  //load the project
  public load(projectId) {
    console.log('Loading Project:' + projectId, Date.now());
    this.http.get('/projects/' + projectId).subscribe(res => this.activeProject.next(res));
    return this.activeProject;
  }

 }

 //component

@Component({
    selector: 'nav',
    template: `<div>{{project?.name}}<a (click)="load('1234')">Load 1234</a></div>`
})
 export class navComponent implements OnInit {
    public project:any;

    constructor(private projectService:ProjectService) {}

    ngOnInit() {
        this.projectService.activeProject.subscribe(active => this.project = active);
    }

    public load(projectId:string) {
        this.projectService.load(projectId);
    }

 }

私はオブザーバーとオブザーバブルの大ファンなので、このアップデートが役立つことを願っています。

元の回答

これは、観察可能な対象またはAngular2EventEmitter

サービスではEventEmitter、値をプッシュできる を作成します。アルファ45で変換する必要がありますtoRx()が、彼らはそれを排除しようとしていたので、アルファ46を単に返すだけで済む場合がありますEvenEmitter

class EventService {
  _emitter: EventEmitter = new EventEmitter();
  rxEmitter: any;
  constructor() {
    this.rxEmitter = this._emitter.toRx();
  }
  doSomething(data){
    this.rxEmitter.next(data);
  }
}

EventEmitterこの方法により、さまざまなサービス機能がプッシュできる単一の方法が得られます。

呼び出しから直接 Observable を返したい場合は、次のようにします。

myHttpCall(path) {
    return Observable.create(observer => {
        http.get(path).map(res => res.json()).subscribe((result) => {
            //do something with result. 
            var newResultArray = mySpecialArrayFunction(result);
            observer.next(newResultArray);
            //call complete if you want to close this stream (like a promise)
            observer.complete();
        });
    });
}

これにより、コンポーネント内で次の操作を実行できるようになります。peopleService.myHttpCall('path').subscribe(people => this.people = people);

そして、サービス内の呼び出しの結果を操作します。

EventEmitter他のコンポーネントからアクセスする必要がある場合に備えて、ストリームを独自に作成することを好みますが、両方の方法が機能していることがわかります...

以下は、イベント エミッターを備えた基本的なサービスを示す plunker です。プランク

おすすめ記事