gpt4 book ai didi

javascript - Ionic 2 等待多个响应

转载 作者:行者123 更新时间:2023-12-03 05:17:37 24 4
gpt4 key购买 nike

我的应用登录页面遇到一些问题。我是 Ionic 2 和 Angular 的新手,我尝试在 Google 的帮助下解决这个问题,但到目前为止还没有成功......

这里的这些行导致了问题,一旦我单击登录按钮,警报就会返回“未定义”,甚至认为它应该等待响应。

let accessToken = this.getAccessToken();
let details = this.getProfileDetails(accessToken);
alert(JSON.stringify(details));

完整代码:

import { Component } from '@angular/core';
import { NavController, Platform } from 'ionic-angular';
import { FbProvider } from '../../providers/fb-provider';
import { TabsPage } from '../tabs/tabs';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Component({
selector: 'page-login',
templateUrl: 'login.html'
})
export class LoginPage {

platform
fb
email
name
id

constructor(public navCtrl: NavController, pf: Platform, fbProvider: FbProvider, public http: Http) {
this.platform = pf;
this.fb = fbProvider;
this.email = '';
this.name = '';
this.id = '';
}

ionViewDidLoad() {
console.log('Hello LoginPage Page');
}

fbLogin() {
let accessToken = this.getAccessToken();
let details = this.getProfileDetails(accessToken);
alert(JSON.stringify(details));
}

getAccessToken(){
this.fb.login().then((fbLoginData) => {
let params = new FormData();
params.append('facebookAccessToken', fbLoginData.authResponse.accessToken);
this.http.post('http://myHostUrl/api/accessToken', params).map(res => res.json())
.subscribe(
data => {
return data.accessToken;
},err => {
alert(err);
}
);
},(err) => {
alert('Facebook login failed');
});
}

getProfileDetails(accessToken){
let params = new FormData();
params.append('accessToken', accessToken);
this.http.post('http://myHostUrl/api/userDetails', params).map(res => res.json())
.subscribe(
data => {
return data;
},err => {
alert(err);
}
);
}

}

最佳答案

它是未定义的,因为您需要等待异步函数完成。以下代码是使用 rxjs 完成的,以管理两个函数和 http 调用的异步。尝试一下。

  fbLogin() {
this.getAccessToken()
.switchMap(accessToken => this.getProfileDetails(accessToken))
.first() // Just one and complete ....
.subscribe(
details => alert(JSON.stringify(details)),
error => alert(error)
);
}

getAccessToken() : Observable<any> {

return Observable.fromPromise(<Promise<any>> this.fb.login())
.map(fbLoginData => fbLoginData.authResponse.accessToken)
.switchMap(accessToken => {
let params = new FormData();
params.append('facebookAccessToken', accessToken);
return this.http.post('http://myHostUrl/api/accessToken', params)
.map(res => res.json())
.map(data => data.accessToken)
});

}

getProfileDetails(accessToken) : Observable<any>{

let params = new FormData();
params.append('accessToken', accessToken);
return this.http.post('http://myHostUrl/api/userDetails', params).map(res => res.json());

}

关于javascript - Ionic 2 等待多个响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41540151/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com