离子3中第一次api调用中的未定义响应 [英] Undefined response in first api call in ionic3

查看:126
本文介绍了离子3中第一次api调用中的未定义响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在ionic3中实现嵌套的api调用

I am trying to implement nested api calls in ionic3

submitLoginForm() {
    var username = this.formData.value.username;
    var password = this.formData.value.password;
    var bodyjson;
    var userId;

    this.ApidataService.logincheck(username,password).subscribe(data => {
        this.logindetail = data;
        bodyjson = JSON.parse(this.logindetail._body);
        userId =  bodyjson.user.id;
        if( userId != undefined){
            this.ApidataService.userdata(userId).subscribe(data => {
                this.userInfo = data;
            });
        }
        console.log(userId);
    });
    console.log(this.userInfo);
}

现在,当我调用此函数时,嵌套的api会在第一次调用时返回undefined然后从第二次调用开始它返回正确的值但是当我尝试记录发送到api的参数时,我注意到每次都传递了正确的值。我认为这是由于一些同步问题,但我无法找出问题和相同的解决方案。

Now when I call this function the nested api returns undefined for the first call and then from the second call onwards it returns proper values however when I try to log the argument that is being sent to the api I notice that the correct value is passed each time. I believe that this is due to some synchronization issues but am unable to figure out the issue and the solution for the same.

推荐答案

你可以在这里使用 flatMap 。似乎你不需要检索两个请求的结果,因此这应该适合你。

You can use flatMap here.It seems you don't need to retrieve results of both requests hence this should work for you.

 import { Observable } from "rxjs/Observable";
 import 'rxjs/add/observable/flatMap';

然后:

 this.ApidataService.logincheck(username,password).flatMap(
  (data) => {
        this.logindetail = data;
        bodyjson = JSON.parse(this.logindetail._body);
        userId =  bodyjson.user.id;
        if( userId != undefined){
          return this.ApidataService.userdata(userId);
        }else{
          return Observable.empty();
        }
    }).map((res: Response) => res ? res.json() : {})
    .subscribe(data => {
           this.userInfo = data ? data : {};
    });

您可以阅读更多关于 flatMap here

You can read more about flatMap here

这篇关于离子3中第一次api调用中的未定义响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆