Ionic 2登录组件和Auth服务 [英] Ionic 2 Login component and Auth service

查看:74
本文介绍了Ionic 2登录组件和Auth服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在我的Ionic 2应用程序中开发一个简单的登录。

I am developing a simple login in my Ionic 2 app.

我有一个登录组件,用于呈现我的登录视图,然后向auth服务发送电子邮件和密码这将验证,保存令牌并返回true或false到登录组件。

I have a login component that renders my login view and then sends email and password to the auth service which will validate, save a token and return true or false to the login component.

我的登录组件:

export class LoginPage {

    email: string;
    password: string;

    constructor(public navCtrl: NavController, public navParams: NavParams, public authentifiction: Authentification) {}

    login() {
        this.authentifiction.login(this.email, this.password);
    }

    loginSuccess() {
        console.log('Success');
    }

    loginError() {
        console.log('Failed');
    }

}

我的身份验证服务:

export class Authentification {

    public authorized: boolean;

    constructor(public http: Http, private alertCtrl: AlertController, public storage: Storage) {}

    login(email, password) {
        var params = 'email=' + email + '&password=' + password;
        var headers = new Headers();
        headers.append('Content-Type', 'application/x-www-form-urlencoded');

        return this.http.post('URL', params, {
            headers: headers})
            .map(res => res.json())
            .subscribe(
                data => this.loginSuccess(data.auth_token),
                error => this.loginError()
        );
    }

    loginSuccess(auth_token) {
        this.storage.set('auth_token', auth_token);
        ???
    }

    loginError() {
        ???
    }

}

如何进行身份验证服务返回true或false取决于登录是否成功?

How can I have the auth service return true or false depending if the login was successful or not?

这整个可观察的事情对我来说仍然有点混乱......

This entire observable thing is still a bit confusing to me...

推荐答案

您不直接返回布尔值,因为http请求不会立即回复。
相反,你向调用者返回一个observable,告诉他我还没有答案,但这里有一个可观察到的,一旦我拥有它就会注意到你的答案。
然后调用者只是订阅这个observable(如邮件列表),并收到一个信号(如接收电子邮件)和答案。

You do not return directly a boolean, because the http request doesn't reply immediatly. Instead, you return an observable to the caller, telling him "I do not have the answer yet but here is an observable that will notice you the answer once I have it". Then the caller just subscribes to this observable (like a mailing list), and receives a signal (like receiving an email) with the answer.

login(email, password): Observable<boolean> {
...
return this.http.post('URL', params, {
  headers: headers
}).map(res => {
  this.storage.set('auth_token', res.json().auth_token);
  return true;
});

来自来电者:

login() {
 this.authentifiction.login(this.email, this.password).subscribe(res => {
   console.log('success');
 }, error => {
   console.log('error');
 });

这篇关于Ionic 2登录组件和Auth服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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