我发现了奇怪的事情。我有 AuthService,它可以保存我的应用程序的身份验证需求,包括身份验证 token 。
@IonicPage()
@Component({
selector: 'page-login',
templateUrl: 'login.html',
})
export class LoginPage {
constructor(public navCtrl: NavController, public navParams: NavParams, public modalCtrl:ModalController,public auth: AuthService) {
}
ionViewDidLoad() {
console.log(this.auth)
console.log(this.auth.loggedIn)
if(this.auth.loggedIn){
console.log(this.auth);
this.navCtrl.push("TabsPage");
}
}
}
当我打电话时
console.log(this.auth)
它返回了authentication 但是当我打电话时
console.log(this.auth.loggedIn)
返回null
这是我的 auth.service.ts
import { Injectable, NgZone, Component } from '@angular/core';
import { Storage } from '@ionic/storage';
// Import AUTH_CONFIG, Auth0Cordova, and auth0.js
import { AUTH_CONFIG } from './auth.config';
import Auth0Cordova from '@auth0/cordova';
import * as auth0 from 'auth0-js';
@Injectable()
export class AuthService {
Auth0 = new auth0.WebAuth(AUTH_CONFIG);
Client = new Auth0Cordova(AUTH_CONFIG);
accessToken: string;
user: any;
loggedIn: boolean;
loading = true;
constructor(
public zone: NgZone,
private storage: Storage
) {
this.storage.get('profile').then(user => this.user = user);
this.storage.get('access_token').then(token => this.accessToken = token);
this.storage.get('expires_at').then(exp => {
this.loggedIn = Date.now() < JSON.parse(exp);
this.loading = false;
});
}
login() {
this.loading = true;
const options = {
scope: 'openid profile offline_access'
};
// Authorize login request with Auth0: open login page and get auth results
this.Client.authorize(options, (err, authResult) => {
if (err) {
throw err;
}
// Set access token
this.storage.set('access_token', authResult.accessToken);
this.accessToken = authResult.accessToken;
// Set access token expiration
const expiresAt = JSON.stringify((authResult.expiresIn * 1000) + new Date().getTime());
this.storage.set('expires_at', expiresAt);
// Set logged in
this.loading = false;
this.loggedIn = true;
// Fetch user's profile info
this.Auth0.client.userInfo(this.accessToken, (err, profile) => {
if (err) {
throw err;
}
this.storage.set('profile', profile).then(val =>
this.zone.run(() => this.user = profile)
);
});
});
}
logout() {
this.storage.remove('profile');
this.storage.remove('access_token');
this.storage.remove('expires_at');
this.accessToken = null;
this.user = null;
this.loggedIn = false;
}
isLoggedIn() :boolean{
return this.loggedIn;
}
}
我正在使用 ionic3 和 auth0 身份验证,以前我认为是我的错,没有在我的属性(property)上使用公共(public)标识符。但是当我将属性更改为公共(public),或创建返回属性的 getter 方法时,它仍然根本不起作用。
最佳答案
这是由于 Chrome 控制台评估对象时造成的。如果您在控制台中打开该对象,您将看到一个微小的蓝色信息图标。这会说:
Value was evaluated just now
基本上发生的情况是,对象内容在您记录它的时间和您在控制台中打开它的时间之间发生了变化。
登录操作是异步的,这意味着将在调用 ionViewDidLoad
后设置 auth 对象上的 loggedIn
属性。也许一件好事是将身份验证设置在 APP_INITIALIZER
中。提供者,或者在您的身份验证上有一些可观察的内容,您可以在其上监听身份验证更改
关于javascript - 对象存在且具有值,但访问时属性返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58620987/