我试图连续进行几个 Web 服务调用,但我遇到的问题是第二次调用将在 .subscribe 在第一次调用执行之前进行。我需要 .subscribe 发生才能设置 this.saveValue,因为 this.saveValue 是在第二次 Web 服务调用的 JSON 中传递的。
此代码当前发生的情况是将进行第一次调用,然后进行第二次调用,然后设置 saveValue。
组件.ts
busy: Subscription;
saveValue: string;
submitButton_Click():void{
try{
// First Web Service Call
this.busy = this.service.firstMethod(this.object)
.first()
.subscribe(result => {
if(result.length > 0){
this.saveValue= result; // VALUE SET FOR USE OF NEXT WEB SERVICE CALL
console.log('Worked');
}
else{
console.log('Failed');
}
})
for(let current of this.array){
let temp= new Object();
temp.id = this.saveValue;
// Second Web Service Call
this.busy = this.service.secondMethod(temp)
.first()
.subscribe(result => {
if(result.valueOf() != false){
console.log('Worked');
}
else{
console.log('Failed');
}
})
}
服务.ts
// First Method
public firstMethod(object: Object): Observable<string>{
return this.client.post<Result>(URL + '/add', object, new Result(), this.token.id)
.map(result => {
let temp = new Object().deserialize(result.data);
return temp.id;
}, this)
.catch(this.handleError);
} // This works and returns proper value
// Second Method (Needs this.saveValue as part of the passed object)
public secondMethod(object: Object): Observable<boolean> {
return this.client.post<Result>(OTHERURL + '/add', object, new Result(), this.token.id)
.map(result => result.success, this)
.catch(this.handleError);
}
感谢您的帮助!
最佳答案
是的,因为您必须等待第一个完成。任何时候你进行异步调用,执行都会愉快地继续下一段代码。像这样尝试:
this.busy = this.service.firstMethod(this.object)
.first()
.subscribe(result => {
if(result.length > 0){
this.saveValue= result; // VALUE SET FOR USE OF NEXT WEB SERVICE CALL
console.log('Worked');
for(let current of this.array){
let temp= new Object();
temp.id = this.saveValue;
// Second Web Service Call
this.busy = this.service.secondMethod(temp)
.first()
.subscribe(result => {
if(result.valueOf() != false){
console.log('Worked');
}
else{
console.log('Failed');
}
})
}
}
else{
console.log('Failed');
}
})
抱歉格式垃圾;我手边没有 WebStorm,没有它我很懒:-)
关于javascript - Angular 2 - 链接 Web 服务调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41654652/