'This' 打字稿未定义

'This' typescript is undefined

我对 ionic / angular / typescript 和 cloudboost 还很陌生,我正在努力使它们协同工作。

我用 "super" 入门主题启动了一个新的离子项目。

我已经成功实现了 cloudboost 登录功能,但是我遇到了一些问题:

如何使打字稿更干净?

这是我的 login.ts 文件:

import { Component } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { ModalController, IonicPage, NavController, ToastController } from 'ionic-angular';

import * as CB from 'cloudboost';
import { User } from '../../providers/providers';
import { MainPage } from '../pages';

import { ModalCguPage } from './modal-cgu';

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



export class LoginPage {
  // The account fields for the login form.
  // If you're using the username field with or without email, make
  // sure to add it to the type
  account: { username: string, password: string } = {
    username: 'defaultuser@defaultsite.co',
    password: '01231234'
  };

  // Our translated text strings
  private loginErrorString: string;
  private loginSuccessString: string;
  private redirectPageSuccess : any = MainPage;

  constructor(public navCtrl: NavController,
    public user: User,
    public toastCtrl: ToastController,
    public translateService: TranslateService,
    public modalCtrl: ModalController) {
    this.translateService.get('LOGIN_ERROR').subscribe((value) => {
      this.loginErrorString = value;
    })
    this.translateService.get('LOGIN_SUCCESS').subscribe((value) => {
      this.loginSuccessString = value;
    })



  }

  // Attempt to login in through our User service
  doLogin() {  
//  HERE : get back the main this to use it later
    var falseThis = this;

//  cloudboost login
    let CBUser = new CB.CloudUser();
    CBUser.set('username', this.account.username);
    CBUser.set('password', this.account.password);
    CBUser.logIn({
        success: function(user) {
            let toast = falseThis.toastCtrl.create({
              message: falseThis.loginSuccessString + ' ' + user.username,
              duration: 3000,
              position: 'top'
            });
            toast.present();

            falseThis.navCtrl.push(MainPage);
        }, error: function(error)  {
    //    error: function(error) {
            // Unable to log in
            let toast = falseThis.toastCtrl.create({
              message: falseThis.loginErrorString,
              duration: 3000,
              position: 'top'
            });
            toast.present();
        }

    });
  }
}

入门模板中包含的原始函数下方:

// Attempt to login in through our User service
  doLogin() {
    this.user.login(this.account).subscribe((resp) => {
      this.navCtrl.push(MainPage);
    }, (err) => {
      this.navCtrl.push(MainPage);
      // Unable to log in
      let toast = this.toastCtrl.create({
        message: this.loginErrorString,
        duration: 3000,
        position: 'top'
      });
      toast.present();
    });
  }

如果有人能把事情搞清楚,我将不胜感激。 谢谢


编辑工作解决方案:

在login.ts

// Attempt to login in through our User service
  doLogin() {
    this.user.login(this.account).then( (user:any) => {
        console.log('user displayed ');
        console.log(user.username);

    //  login successful
        let toast = this.toastCtrl.create({
          message: this.loginSuccessString + user.username,
          duration: 3000,
          position: 'top'
        });
        toast.present();

        this.navCtrl.push(MainPage);
    }).catch( err => {
    // Unable to log in
      let toast = this.toastCtrl.create({
        message: this.loginErrorString,
        duration: 3000,
        position: 'top'
      });
      toast.present();
    });
  }

在 user.ts 中:

login(account: any) {
         let CBUser = new CB.CloudUser();
         CBUser.set('username', account.username);
         CBUser.set('password', account.password);
         return new Promise((resolve, reject) =>{
             CBUser.logIn({
                 success: (user) => {
                 //Login successful
                     resolve(user)
                 },
                 error: (error) => {
                     reject(error)
                 //Error in user login.
                 }
             });
         });
     }

该示例使用箭头 lambda,它改变了 this 发生的规则。查看 this article 了解详情。

success: function(user) {
  //this not accessible
}

success: user => {
  //this is accessible
}

I can't access this in the callback function of CBUser.logIn, it is undefined. I tried several way with the fat arrow, but didn't work, so at the moment, I managed with this workaround

我认为佩斯回答了这个问题。这 link 在我遇到这个问题时帮助了我 arrow functions

对于 CloudBoost 回调,请使用:

{
  success: (obj) => {
    //success
  },
  error: (err) => {
    //Error
  }
}

I didn't succeed to use the user provider as it is using Http service and Cloudboost does not give access to an url, and the original return is an observable.

用户提供程序只是启动 Http 请求的示例。要将用户提供程序与 cloudboost 一起使用,我建议将登录功能更改为

login(account) {
let CBUser = new CB.CloudUser();
CBUser.set('username', account.username);
CBUser.set('password', account.password);
return new Promise((resolve, reject) =>{
  CBUser.logIn({
    success: (user) => {
      //Login successful
      resolve(user)
    },
    error: (error) => {
      reject(error)
      //Error in user login.
    }
  })
 })
}

并调用函数:

this.user.login(this.account).then( user => {
  //login successful
  this.navCtrl.push(MainPage);
}).catch( err => {
  this.navCtrl.push(MainPage);
  // Unable to log in
  let toast = this.toastCtrl.create({
    message: this.loginErrorString,
    duration: 3000,
    position: 'top'
  });
  toast.present();
});