Ionic httpClient 响应使用 toast

Ionic httpClient response use toast

我将登录数据发送到服务,在 login.ts 中得到响应后 toast 未定义,如何解决?

我在另一个函数中尝试我的 toast 函数,但它的工作没有条件

this my function for load service login.ts:

import { Component, OnInit } from '@angular/core';
import { NavController, MenuController, PopoverController } from "ionic-angular";
import { TabsInfluencerComponent } from '../../influencer/tabs/tabs';
import { RegisterComponent } from '../register/register';
import { ResetComponent } from '../reset/reset';
import { OfferComponent } from '../../advertiser/offer/offer';
import { ngForm } from '@angular/forms';
import { AuthService } from '../../../services/auth';
import { ToastController } from 'ionic-angular';



@Component({
    templateUrl: 'login.component.html',

})

export class LoginComponent implements OnInit {

    constructor(
        public nav:NavController, 
        public menu:MenuController, 
        public popover: PopoverController, 
        private AuthService : AuthService, 
        private toastCtrl: ToastController) {

    }   

    responseData : any;
    public isChoose: boolean = false;
    public isshowP: boolean = false;
    //login and get data in service
    login(form: ngForm){
        this.AuthService.login(form.value.email, form.value.password)
        .then(function(data) {
            if(data.success == true){
                localStorage.setItem('userToken',data.token);
                localStorage.setItem('userData',JSON.stringify(data.user));
            }else{
                let toast = this.toastCtrl.create({
                  message: data.error,
                  duration: 3000
                });
                toast.present();
            }
        })
        .catch(function(error) {
            console.log(error);
        })
    }


}

this my service auth.ts:

    import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { map } from 'rxjs/operators'


@Injectable()
export class AuthService {
    private loginUrl : string = 'http://localhost:8000/api/login';
    data : any;
    constructor(private http: HttpClient){}
    //function for login
    login(email : string, password :string){
        const body = {email : email, password : password};
        return new Promise(resolve => {
          this.http.post(this.loginUrl, body)
            .subscribe(data => {
              this.data = data;
              resolve(this.data);
            });
        });
    }

    register(email : string, password :string){

    }
}

在 运行 之后我有这样的错误: TypeError: 无法读取未定义的 属性 'toastCtrl'

在这种情况下,您的 login.ts.

中的 this 引用有问题
.then(function(data) {
    ...
    let toast = this.toastCtrl.create({
        message: data.error,
        duration: 3000
    });
    ...
})

this 引用了您的 then 块中的匿名函数,但您想引用回您的 LoginComponent class.

如何解决?

你可以使用现在非常流行的箭头函数。

.then((data) => {
    ...
    let toast = this.toastCtrl.create({
        message: data.error,
        duration: 3000
    });
    ...
})