【问题标题】:ReactiveX Observable to trigger when I want toReactiveX Observable 在我想触发时触发
【发布时间】:2017-03-19 09:02:54
【问题描述】:

我尝试像点击和间隔一样触发 Observable。怎么触发?

我尝试了 obs.retry(),但它什么也没做。

constructor(private http: Http) {
    this.obs = this.http.get('http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1');
    obs.subscribe((response) => {
        console.log(response.text());
    })
    setInterval(() => {
        console.log('update');
        this.obs.retry();
    }, 1000)
}

onClick() {
   console.log('click');
   this.obs.retry();
}

【问题讨论】:

    标签: observable reactivex


    【解决方案1】:

    当你想“重试”时,你必须重新订阅。

    当你构造一个 observable 时,比如当你做 this.http.get(...) 时,你只是在定义你想要对数据做什么。所以你说“我想从服务器获取数据,然后过滤掉我不想要的数据 (.filter(...)) 并将其映射到我的对象定义以便我可以使用它 (.map(...))”,但是目前还没有采取任何这些行动。

    当你 .subscribe() 到那个 observable 时,你正在运行你刚刚定义的所有这些操作。所以在这种情况下,你应该这样做:

    constructor(private http: Http) {
        this.obs = this.http.get('http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1');
    
        setInterval(() => {
            console.log('update');
            this.loadPosts();
        }, 1000)
    }
    
    loadPosts() {
        this.obs.subscribe((response) => {
            console.log(response.text());
        });
    }
    
    onClick() {
        console.log('click');
        this.loadPosts();
    }
    

    如果您了解这部分,那么您可以考虑将其作为完整的 Rx 解决方案:

    constructor(private http: Http) {
        let httpStream = this.http.get('http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1');
        this.clickSubject = new Rx.ReplaySubject(1);
    
        this.obs = Rx.Observable.interval(1000)
            .merge(this.clickSubject)
            .flatMap(() => httpStream);
    
        // Note that is not a good practice to have subscribe in constructors, should have this in init() method or something similar.
        this.obs.subscribe(() => {
            console.log(response.text());
        });
    }
    
    onClick() {
        console.log('click');
        this.clickSubject.onNext();
    }
    

    在这里,我设置了一个每秒滴答的流 (Rx.Observable.interval),将该流与每次点击时都会产生的流连接起来 (this.clickSubject),并将每个滴答映射为 @987654329 的新结果@。

    【讨论】:

    • 非常感谢,还在学习,但是非常感谢,需要一些时间才能掌握,因为我正在使用 ng2 / material2 加上这个来学习很多东西。我保存了这么多!喂!
    • 如果你认为这个答案解决了你的问题,你可以在它上面打上绿色的勾,将它标记为接受的答案(如果你这样做,我会得到更多的声誉哈哈)
    猜你喜欢
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多