如何使用angular2发出异步请求?
我对ionic2、angular2和typeScript非常陌生。如何使用angular2发出异步请求?,angular,typescript,ionic2,Angular,Typescript,Ionic2,我对ionic2、angular2和typeScript非常陌生。 我正在尝试设置一个离子登录页面,该页面检索登录凭据并通过AuthService联系远程api进行身份验证。 序列图如下所示: login.html-----1-----login.ts------2------AuthService-------3-----remoteAPI | || | | | | |
我正在尝试设置一个离子登录页面,该页面检索登录凭据并通过AuthService联系远程api进行身份验证。 序列图如下所示:
login.html-----1-----login.ts------2------AuthService-------3-----remoteAPI
| || | | | |
| || | | | |
-----6(if error)---- | --------5-------- ------4-----------
|
HomePage----------6-------
关于登录页面组件:login.html
<ion-content class="login-content" padding>
<ion-row class="logo-row">
<ion-col></ion-col>
<ion-col width-67>
<img src="logo.jpg"/>
</ion-col>
<ion-col></ion-col>
</ion-row>
<div class="login-box">
<form #loginForm="ngForm">
<ion-row>
<ion-col>
<ion-list inset>
<ion-item>
<ion-input type="tel" placeholder="Téléphone" name="phoneNumber" [(ngModel)]="loginCredentials.phoneNumber" required></ion-input>
</ion-item>
<ion-item>
<ion-input type="password" placeholder="Password" name="password" [(ngModel)]="loginCredentials.password" required></ion-input>
</ion-item>
</ion-list>
</ion-col>
</ion-row>
<ion-row>
<ion-col class="signup-col">
<button ion-button class="submit-btn" full (click)="login()" [disabled]="!loginForm.form.valid">Login</button>
<button ion-button class="register-btn" block clear (click)="createAccount()">Create New Account</button>
</ion-col>
</ion-row>
</form>
</div>
</ion-content>
import { Component } from '@angular/core';
import { NavController, AlertController, LoadingController, Loading } from 'ionic-angular';
import { AuthService } from '../../providers/auth-service';
import { RegisterPage } from '../register/register';
import { HomePage } from '../home/home';
@Component({
selector: 'page-login',
templateUrl: 'login.html'
})
export class LoginPage {
loading: Loading;
loginCredentials = {phoneNumber: '', password: ''};
retrievedData: any;
constructor(private nav: NavController, private auth: AuthService, private alertCtrl: AlertController, private loadingCtrl: LoadingController) {}
public createAccount() {
this.nav.push(RegisterPage);
}
public login() {
this.showLoading();
this.auth.login(this.loginCredentials).subscribe(
retrievedData => {
if (retrievedData) {
setTimeout(() => {
this.loading.dismiss();
console.log(retrievedData.message);
this.nav.setRoot(HomePage)
});
} else {
this.showError("Accès refusé");
}
},
error => {
this.showError(error);
});
}
showLoading() {
this.loading = this.loadingCtrl.create({
content: 'Patientez...'
});
this.loading.present();
}
showError(text) {
setTimeout(() => {
this.loading.dismiss();
});
let alert = this.alertCtrl.create({
title: 'Echec',
subTitle: text,
buttons: ['OK']
});
alert.present(prompt);
}
}
import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
export class User {
phoneNumber: string;
gender: String;
constructor(phoneNumber: string, password: string, gender: string) {
this.phoneNumber = phoneNumber;
this.gender = gender;
}
}
@Injectable()
export class AuthService {
currentUser: User;
connectUseralias = 'localhost:8080/thravvel-core/rest/users/connect';
constructor(public http: Http) {
console.log('Hello Authservice Provider');
}
public login(credentials): Observable<any> {
if (credentials.phoneNumber === null || credentials.password === null) {
return Observable.throw("Please insert credentials");
} else {
console.log(`About to process request ${this.connectUseralias }?phoneNumber=${credentials.phoneNumber}&password=${credentials.password}`);
return this.http.get(`${this.connectUseralias }?phoneNumber=${credentials.phoneNumber}&password=${credentials.password}`)
.map(this.handleResponse)
.catch(this.handleError);
}
}
private handleResponse(res: Response) {
let body = res.json();
console.log(body);
return body.data || { };
}
private handleError(error: Response | any) {
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
return Observable.throw(errMsg);
}
}
验证服务.ts
<ion-content class="login-content" padding>
<ion-row class="logo-row">
<ion-col></ion-col>
<ion-col width-67>
<img src="logo.jpg"/>
</ion-col>
<ion-col></ion-col>
</ion-row>
<div class="login-box">
<form #loginForm="ngForm">
<ion-row>
<ion-col>
<ion-list inset>
<ion-item>
<ion-input type="tel" placeholder="Téléphone" name="phoneNumber" [(ngModel)]="loginCredentials.phoneNumber" required></ion-input>
</ion-item>
<ion-item>
<ion-input type="password" placeholder="Password" name="password" [(ngModel)]="loginCredentials.password" required></ion-input>
</ion-item>
</ion-list>
</ion-col>
</ion-row>
<ion-row>
<ion-col class="signup-col">
<button ion-button class="submit-btn" full (click)="login()" [disabled]="!loginForm.form.valid">Login</button>
<button ion-button class="register-btn" block clear (click)="createAccount()">Create New Account</button>
</ion-col>
</ion-row>
</form>
</div>
</ion-content>
import { Component } from '@angular/core';
import { NavController, AlertController, LoadingController, Loading } from 'ionic-angular';
import { AuthService } from '../../providers/auth-service';
import { RegisterPage } from '../register/register';
import { HomePage } from '../home/home';
@Component({
selector: 'page-login',
templateUrl: 'login.html'
})
export class LoginPage {
loading: Loading;
loginCredentials = {phoneNumber: '', password: ''};
retrievedData: any;
constructor(private nav: NavController, private auth: AuthService, private alertCtrl: AlertController, private loadingCtrl: LoadingController) {}
public createAccount() {
this.nav.push(RegisterPage);
}
public login() {
this.showLoading();
this.auth.login(this.loginCredentials).subscribe(
retrievedData => {
if (retrievedData) {
setTimeout(() => {
this.loading.dismiss();
console.log(retrievedData.message);
this.nav.setRoot(HomePage)
});
} else {
this.showError("Accès refusé");
}
},
error => {
this.showError(error);
});
}
showLoading() {
this.loading = this.loadingCtrl.create({
content: 'Patientez...'
});
this.loading.present();
}
showError(text) {
setTimeout(() => {
this.loading.dismiss();
});
let alert = this.alertCtrl.create({
title: 'Echec',
subTitle: text,
buttons: ['OK']
});
alert.present(prompt);
}
}
import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
export class User {
phoneNumber: string;
gender: String;
constructor(phoneNumber: string, password: string, gender: string) {
this.phoneNumber = phoneNumber;
this.gender = gender;
}
}
@Injectable()
export class AuthService {
currentUser: User;
connectUseralias = 'localhost:8080/thravvel-core/rest/users/connect';
constructor(public http: Http) {
console.log('Hello Authservice Provider');
}
public login(credentials): Observable<any> {
if (credentials.phoneNumber === null || credentials.password === null) {
return Observable.throw("Please insert credentials");
} else {
console.log(`About to process request ${this.connectUseralias }?phoneNumber=${credentials.phoneNumber}&password=${credentials.password}`);
return this.http.get(`${this.connectUseralias }?phoneNumber=${credentials.phoneNumber}&password=${credentials.password}`)
.map(this.handleResponse)
.catch(this.handleError);
}
}
private handleResponse(res: Response) {
let body = res.json();
console.log(body);
return body.data || { };
}
private handleError(error: Response | any) {
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
return Observable.throw(errMsg);
}
}
这就是错误所在:./LoginPage类LoginPage-内联模板中的错误:28:10原因:发生网络错误 使用原始STACKTRACE:
ErrorHandler.prototype.handleError http://localhost:8100/build main.js:52225:13
PlatformRef_.prototype._bootstrapModuleFactoryWithZone/</<.next http://localhost:8100/build/main.js:33833:65
EventEmitter.prototype.subscribe/schedulerFn< http://localhost:8100/build/main.js:35343:36
SafeSubscriber.prototype.__tryOrUnsub http://localhost:8100/build/main.js:19899:13
SafeSubscriber.prototype.next http://localhost:8100/build/main.js:19848:17
Subscriber.prototype._next http://localhost:8100/build/main.js:19801:9
Subscriber.prototype.next http://localhost:8100/build/main.js:19765:13
Subject.prototype.next http://localhost:8100/build/main.js:19565:17
EventEmitter.prototype.emit http://localhost:8100/build/main.js:35335:54
NgZone.prototype.triggerError http://localhost:8100/build/main.js:36185:56
NgZone.prototype.forkInnerZoneWithAngularBehavior/this.inner<.onHandleError http://localhost:8100/build/main.js:36164:17
O</d</t.prototype.handleError http://localhost:8100/build/polyfills.js:3:9172
O</v</e.prototype.runTask http://localhost:8100/build/polyfills.js:3:7118
t/this.invoke http://localhost:8100/build/polyfills.js:3:10834
ErrorHandler.prototype.handleErrorhttp://localhost:8100/build main.js:52225:13
PlatformRef.prototype.\u bootstrapModuleFactoryWithZone/能否在handleResponse和handleError回调函数中添加日志?然后打印出错误或res?嗯,您正试图向本地主机发送请求:8080/thravvel core/rest/users/connect
。这不是有效的URL。有效的URL应该是http://localhost:8080/thravvel-核心/休息/用户/连接
。而且,我真的,真的不会用GET发送凭证。可以在服务器(和代理等)的日志中查看密码。使用POST.ooh my good@JBNizet,你刚刚救了我一天,我怎么会忘记协议?关于方法,我完全同意你,我会改变它,谢谢!!