简体   繁体   English

如何使用Angular2链接2个可观察对象

[英]How to chain 2 Observables with Angular2

I trying to do the following without success. 我试图做以下没有成功的事情。 I am trying fire an http request/Observable depending on a previous http request result. 我正在尝试根据先前的HTTP请求结果触发一个HTTP请求/可观察到。

ngOnInit() {
    this._lights.LastChannel(this.hostname).subscribe(data => {
        this.LastChannel = data.Message;
        this.shields = this.LastChannel / 8;
        if (this.LastChannel % 8 != 0){
            this.shields++;
        }
        for(var i=0; i < this.shields; i++){
            console.log(i+1);
            this.shield(i+1)
        }
    });
}
shield(index){
    this._lights.shieldStatus(this.hostname, index)
        .subscribe(data=> {
            console.log(data.Message.split(' '));
            console.log(data.Message)
        })
}

First request runs fine, second one gets fired. 第一个请求运行正常,第二个被触发。 Go server responds 200, but browser shows keep pending. Go服务器响应200,但浏览器显示保持挂起状态。

You need the flatMap operator for this 您需要为此的flatMap运算符

this._lights.LastChannel(this.hostname).flatMap(
  (data) => {
    let params: URLSearchParams = new URLSearchParams();
    params.set('access_token', localStorage.getItem('access_token'));
    return this._lights.shieldStatus(this.hostname, data.messages).map((res: Response) => res.json());
  }
);

@ThierryTempiler answered this question here: Angular 2: Two backend service calls on success of first service @ThierryTempiler在这里回答了这个问题: 角度2:首次服务成功时两个后端服务调用

You need to create a third service function that would join both the requests using Observable.forkJoin . 您需要创建第三个服务函数,该函数将使用Observable.forkJoin将两个请求连接在一起。

initial (device){
        var obs = this.LastChannel(device).flatMap(
            (data) => {
                return Observable.forkJoin([
                    Observable.of(data),
                    this.shieldStatus(device, data)
                ]);
            }
        );
        return obs;
    }

then I can call it like 那我可以这样称呼它

ngOnInit() {
    this._lights.initial(this.hostname).subscribe(data=> console.log(data))
}

and this data is an array of both the request's response. 并且此数据是两个请求响应的数组。

Array[2]
0
:
Object
Message
:
"64"
Time
:
"2016-05-14T09:13:12.416400176-03:00"

1
:
Object
Message
:
"false false false false false true true true"
Time
:
"2016-05-14T09:13:12.797315391-03:00"

:
2
__proto__
:
Array[0]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM