如何在参数更改时重新触发HTTP调用?

时间:2018-05-02 21:27:19

标签: angular rxjs

我有一个服务方法,它使用传递给它的参数触发HTTP调用。它有效,没有麻烦。

我需要做的是让我的组件在这些参数发生变化时重新触发该调用。我仍然在处理可观察物和RxJS,所以我不知道该怎么做。我已将参数设置为主题,并在每次更改时将这些参数的新对象发送给它。所以,如果我订阅参数Subject,我该如何最好地重新启动HTTP调用?重新订阅每个更改似乎非常混乱。

3 个答案:

答案 0 :(得分:1)

为什么不使用switchMap()?有了它,您不需要处理任何订阅,直到您的组件被拆除。

export class MyComponent implements OnInit {
    //remember to inject your service properly
    ngOnInit() {
        this.myService.parametersChange$
            .asObservable()
            .switchMap(params => this.http.get(`/do/something/with/your/{params}`))
            .subscribe(x => console.log(x))//handle your http
    }
}

答案 1 :(得分:0)

我认为你几乎就在那里,只需订阅你的主题,每当你从中获得一个新值时,就拨打一个Http电话。

你也是对的,因为你需要订阅实际触发你的http电话,你每次都会被迫重新订阅。要进行优化,您可以跟踪您的http呼叫订阅,并在每次参数更改时取消订阅,这样您就不会跟踪“旧”请求。

类似的东西:

export class MyComponent implements OnInit {
    parametersChange$: Subject;
    httpSubscription: Subscription;

    ngOnInit () {
       this.parametersChange$.subscribe(params => {
           if (this.httpSubscription) {
              this.httpSubscription.unsubscribe();
           }
           this.httpSubscription = this.http.get(...).subscribe(// do your stuff);
       });
    }
}

希望有所帮助

答案 2 :(得分:0)

您是否期待来自http电话的答案流?如果没有,那么做以下事情可能会更清晰:

export class MyComponent implements OnInit {
    parametersChange$: Subject;
    httpResult

    ngOnInit () {
       this.parametersChange$.subscribe(async params => {
           this.httpResult = await this.http.get(params).toPromise();
       });
    }
}

相关问题