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();

我需要通过 args currentPage,我该如何解决?

4

1 回答 1

2

查看您的代码后有几点。

_load = new Subject();类型参数(或泛型类型,如果你愿意的话)被省略了,所以_load实际上是默认类型Subject<any>(又名Subject<{}>)。在我看来fetchPosts,你期望它是类型any[],甚至可能是[number, string, string].

您是否会编写_load = new Subject<any[]>();并且fetchPosts(args: any[])typescript 会产生类型错误,因为行:.scan((currentPage) => currentPage + 1, 0) 将类型参数从 typeany转换为 type number。此扫描操作对输入没有任何作用,只是从主题接收输入的每种类型currentPage开始增加一个数字。0如果你然后输入这个数字并args尝试fetchPosts记录args[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 回答