Typescript rxjs在Subject.next中传递参数
我是rxjs新手,我正在尝试在Typescript rxjs在Subject.next中传递参数,typescript,rxjs,subject,Typescript,Rxjs,Subject,我是rxjs新手,我正在尝试在主题中传递参数。下一步(args)我有以下类: @Injectable() export class ListPosts { baseURL: string = 'http://localhost/wptest/api'; _load = new Subject(); constructor(private http: Http) { var currentPage = this._load .scan((currentPage) =>
主题中传递参数。下一步(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.\u load
,它会工作
var postResponses = this._load
.flatMap(args => this.fetchPosts(args)) //args here is defined
.share();
我需要通过
currentPage
获取参数,如何修复它?查看您的代码后,有几点需要注意
在中加载=新主题()
类型参数(或泛型类型,如果您愿意)被省略,因此\u load
实际上是默认类型Subject
(也称Subject)
。在我看来,通过查看fetchPosts
,您似乎希望它属于any[]
类型,甚至可能是[number,string,string]
你会写\u load=new Subject()
和fetchPosts(args:any[])
typescript会产生类型错误,因为行:.scan((currentPage)=>currentPage+1,0)
将类型参数从typeany
转换为typenumber
。此扫描操作对输入不起任何作用,只需从受试者收到输入的每种类型的0
开始增加一个数字currentPage
。如果您随后将此数字作为args
输入fetchPosts
,并尝试记录args[0]
,args[1]
和args[2]
,您将得到未定义的
,因为数字不是数组。如果您记录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]]
);
type Args=[number,string,string];
const_load=new Rx.Subject();
const\u loadCount=\u load.scan(count=>count+1,0);
const\u loadWithCount=Rx.Observable.zip(\u load,\u loadCount,
(args,count):args=>[count,args[1],args[2]]
);
您在尝试运行代码时是否遇到任何错误?在扫描()之后,您希望currentPAge设置为什么?@bstockwell I get args未定义。currentPage和其他变量用于计算加载了多少帖子,比如加载了5/38帖子
,并在完成38/38
”后禁用“加载更多”按钮。扫描((currentPage)=>currentPage+1,0)将类型参数从类型any转换为类型number。“这也是我所想的。”,但我对typescript还不太熟悉,不知道是否真的是这样。回答得好,谢谢。Typescript的类型推断工作得很好。通过扫描,第二个参数的类型与可观察对象的类型参数匹配。谢谢@LodewijkBogaards,这个类就像angular2中的一个子组件
count这里指的是我希望在每次单击“loadmore”时显示的帖子数,您所说的仅记录args
是正确的,但不是我想要实现的,我只想把args
从functionloadMore
传递到functionfetchPost
。我忘了提到它是rxjs 5 alpha 14,然后简单地把放在平面图之前的currentPage
位置。我已经解释了为什么你会有这样的行为。如果希望args
保持不变,只需订阅\u load
,因为scan
会更改流。