1

私はrxjsを初めて使用します。パラメーターを渡そうとしSubject.next(args)ています。次のクラスがあります。

@Injectable()
export class ListPosts {
baseURL: string = 'http://localhost/wptest/api';
_load = new Subject();

constructor(private http: Http) {
    var currentPage = this._load
        .scan((currentPage) => currentPage + 1, 0)

    var postResponses = currentPage           //args here is undefined
        .flatMap(args => this.fetchPosts(args))
        .share();

    var loadedPosts = postResponses
        .map(json => json.posts)
        .scan((allPosts, newPosts) => allPosts.concat(newPosts), []);

    this.loadedPostCount = loadedPosts.map(p => p.length);
    this.totalPostCount = postResponses.map(json => json.count_total);

    this.completed = Observable.combineLatest(this.loadedPostCount, this.totalPostCount, (loaded, total) => loaded >= total);

    this.posts = loadedPosts;
}

fetchPosts(args: any) {
    console.log("count: " + args[0] + " page :" + args[1] + " type: "+ args[2]);
}

loadMore(args: any) {
    this._load.next(args);
}
}

しかし、に変更currentPageするthis._loadと動作します

var postResponses = this._load
        .flatMap(args => this.fetchPosts(args)) //args here is defined
        .share();

経由で引数を取得する必要がありますcurrentPage。どうすれば修正できますか?

4

1 に答える 1

2

コードを見た後、いくつかのポイントがあります。

型パラメーター (または必要に_load = new Subject();応じてジェネリック型) は省略されているため、_load実際には既定の型Subject<any>(別名Subject<{}>).fetchPostsany[]またはおそらく[number, string, string].

行: が型パラメーターを typeからtype に 変換するため_load = new Subject<any[]>();、typescriptfetchPosts(args: any[])は型エラーを生成します。このスキャン操作は入力に対して何も行いませんが、サブジェクトが入力を受け取るすべてのタイプに対してから始まる数値を増やすだけです。次に、この数値をtoとして入力して をログに記録しようとすると、数値は配列ではないため、が得られます。自分自身をログに記録すると、 currentPage 番号が表示されることがわかります。.scan((currentPage) => currentPage + 1, 0)anynumbercurrentPage0argsfetchPostsargs[0]args[1]args[2]undefinedargs

これはあなたのために働くかもしれない、またはあなたのソリューションがどのように機能するかについてのアイデアを与えるかもしれないものです:

  type Args = [number, string, string];
  const _load = new Rx.Subject<Args>();
  const _loadCount = _load.scan(count => count + 1, 0);
  const _loadWithCount = Rx.Observable.zip(_load, _loadCount,
    (args, count) : Args => [count, args[1], args[2]]
  );
于 2015-12-12T14:56:15.680 に答える