Subject.next 中的 rxjs 传递参数

rxjs pass parameter in Subject.next

我是 rxjs 的新手,我正在尝试在 Subject.next(args) 中传递参数 我有以下 class:

@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 获取参数,我该如何解决?

看了你的代码后有几点。

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

你写的 _load = new Subject<any[]>();fetchPosts(args: any[]) 打字稿会产生类型错误吗,因为行:.scan((currentPage) => currentPage + 1, 0) 将类型参数从类型 any 转换为类型number。此扫描操作对输入没有任何作用,只是简单地为主题接收输入的每种类型增加一个从 0 开始的数字 currentPage。如果您随后将此数字作为 args 提供给 fetchPosts 并尝试记录 args[0]args[1]args[2],您将得到 undefined,因为数字不是数组。如果您自己登录 args,您会发现您会看到当前页码。

以下内容可能对您有用,或者可以让您了解您的解决方案如何工作:

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