Javascript Ionic 3:在第二次GET调用中使用JSON响应的结果

Javascript Ionic 3:在第二次GET调用中使用JSON响应的结果,javascript,angular,typescript,ionic3,Javascript,Angular,Typescript,Ionic3,因此,我的应用程序获取输入并将其转换为字符串,调用json并获取响应,部分响应(前2行)如下所示: 现在我需要使我的代码异步,它调用这个,等待响应,获取那个“id”,将它存储到一个变量中,以便在第二次调用中使用,这是我目前使用的不起作用的代码。(对于当前代码,它甚至不是异步的,因为它总是尝试从未定义中获取id。) grabRAW(电子邮件){ this.grabID(电子邮件).subscribe(数据=>{ this.idList=data.data; }); 设id=this.idLis

因此,我的应用程序获取输入并将其转换为字符串,调用json并获取响应,部分响应(前2行)如下所示:

现在我需要使我的代码异步,它调用这个,等待响应,获取那个“id”,将它存储到一个变量中,以便在第二次调用中使用,这是我目前使用的不起作用的代码。(对于当前代码,它甚至不是异步的,因为它总是尝试从未定义中获取id。)

grabRAW(电子邮件){
this.grabID(电子邮件).subscribe(数据=>{
this.idList=data.data;
});
设id=this.idList[0].id;
返回this.http.get(((this.url1.concat(id)).concat(this.url2))
.map((res:Response)=>res.json())
.do((res:Response)=>console.log(res))
}
grabID(电子邮件){
返回this.http.get(this.url.concat(电子邮件))
.map((res:Response)=>res.json())
.do((res:Response)=>console.log(res))

}
您可以像这样使用而不是订阅第一个可观察对象:

import { Observable } from 'rxjs/Observable';
import { switchMap }  from 'rxjs/add/operator/switchMap';

// ...

grabRAW(email): Observable<any> {
    return this.grabID(email)
               .switchMap(data => {
                   this.idList = data.data;
                   let id = this.idList[0].id;

                   // Now send the second http request
                   return this.http.get(((this.url1.concat(id))).concat(this.url2))
                              .map((res: Response) => res.json())
                              .do((res:Response) => console.log(res))
        });
}

grabID(email): Observable<any> {
    return this.http.get(this.url.concat(email))
        .map((res: Response) => res.json())
        .do((res:Response) => console.log(res))
}
从'rxjs/Observable'导入{Observable};
从'rxjs/add/operator/switchMap'导入{switchMap};
// ...
grabRAW(电子邮件):可观察{
返回此.grabID(电子邮件)
.switchMap(数据=>{
this.idList=data.data;
设id=this.idList[0].id;
//现在发送第二个http请求
返回this.http.get(((this.url1.concat(id)).concat(this.url2))
.map((res:Response)=>res.json())
.do((res:Response)=>console.log(res))
});
}
grabID(电子邮件):可观察{
返回this.http.get(this.url.concat(电子邮件))
.map((res:Response)=>res.json())
.do((res:Response)=>console.log(res))
}

感谢您的回答,因此首先我必须从rjxs导入switchmap,但这没问题,但随后我出现了错误,无法读取属性subscribe of undefined,因此我在原始帖子中添加了调用此服务提供商的原始TS代码,希望您能帮助我:)ThanksI使用import'rxjs/add/operator/switchmap'导入了switchmap;btwI已经编辑了答案,在每个方法上添加了返回的类型(
Observable
)。如果可以解决问题,请尝试一下。您需要在文件顶部添加导入:
import{Observable}from'rxjs/Observable'。我在答案中添加了两个导入:)哦,缺少一个
return
语句:
returnthis.grabID(email)…
。我已经编辑了答案来修复它。对于所有问题,我深表歉意:(