我正在尝试在一行中进行一些Web服务调用,但是我遇到的问题是第二次调用将在.subscribe执行第一次调用之前发生。我需要.subscribe才能设置this.saveValue,因为this.saveValue是在第二个Web服务调用的JSON中传递的。Angular 2 - 链接Web服务调用
这段代码当前正在发生的事情是,第一次调用将被创建,然后第二次调用将被创建,然后saveValue被设置。
Component.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');
}
})
}
Service.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);
}
感谢您的帮助!