如何使用angular2进行异步请求?

时间:2017-03-11 05:08:05

标签: angular typescript ionic2

我对ionic2,angular2和typeScript很新 我正在尝试设置一个离子登录页面,该页面检索登录凭据并通过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>  

login.ts

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);
  }
}

auth-service.ts

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);

  }
}

当我点击登录按钮时,日志&#34;即将处理请求...&#34;记录良好,但请求没有发送,(浏览器检查网络选项卡没有任何内容!!!),这意味着流程在此指令失败:return

this.http.get(`${this.connectUseralias }?phoneNumber=${credentials.phoneNumber}&password=${credentials.password}`)
            .map(this.handleResponse)
            .catch(this.handleError);

这是错误:
./LoginPage类中的错误LoginPage - 内联模板:28:10导致:发生网络错误

使用ORIGINAL 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  

我不知道从哪里开始调试,我确实花了很多时间在它身上,不知道问题是什么。
真的需要帮助!!

0 个答案:

没有答案