Javascript Aurelia:数据未定义
我需要帮助从一个aurelia页面到另一个页面获取数据。 我在登录页面上询问用户名和密码。然后我检查这个用户是否在数据库中。问题是,我不知道如何在接下来的页面中记住用户名。我需要这里的用户名:Javascript Aurelia:数据未定义,javascript,aurelia,Javascript,Aurelia,我需要帮助从一个aurelia页面到另一个页面获取数据。 我在登录页面上询问用户名和密码。然后我检查这个用户是否在数据库中。问题是,我不知道如何在接下来的页面中记住用户名。我需要这里的用户名: import {HttpClient, json} from 'aurelia-fetch-client' export class User{ constructor(userData){ this.username= userData.username; } userData = {} u
import {HttpClient, json} from 'aurelia-fetch-client'
export class User{
constructor(userData){
this.username= userData.username;
}
userData = {}
userList= []
getUser(x, y){
console.log(x)
this.username = x;
console.log(y)
let client = new HttpClient();
client.fetch('http://localhost:8080/users/'+ x)
.then(response => response.json())
.then(data => {
if(JSON.stringify(data.password) === '"'+y+'"'){
console.log("Okei")
var landingUrl = "http://" + window.location.host + "#/main";
window.location.href = landingUrl
}else{
console.log("Wrong password")
alert("Wrong password! Try again")
}
})
}
}
至该页:
import {HttpClient, json} from 'aurelia-fetch-client'
import { inject } from 'aurelia-framework'
import { User } from '../home/index';
@inject(User)
export class Diet{
constructor(userData) {
this.username = userData.username;
}
somethingSpecial() {
console.log(this.username);
}
dietData = {}
dietList=[]
addDiet(){
let client = new HttpClient();
client.fetch('http://localhost:8080/diet/add', {
'method': "POST",
'body': json(this.dietData)
})
.then(response => response.json())
.then(data => {
console.log("Server sent " + data.foodName);
});
document.getElementById("form").reset();
this.somethingSpecial();
}
}
我尝试过使用构造函数,但是现在它说userData是未定义的,所以它不能从第一页获取信息。我做错了什么?
谢谢大家! 使用单例。在Aurelia中,这就像创建一个类并注入它一样简单 以我自己的一个应用程序中的以下简化示例为例 注:这本来是打字稿,但我想我是对的
import { inject } from 'aurelia-framework';
import { HttpClient } from 'aurelia-http-client';
@inject(HttpClient)
export class Auth {
constructor(http) {
this.http
.get('/api/auth/userinfo')
.then(response => {
this.userInfo = response.content;
});
}
}
完成此操作后,您可以从任何地方调用此类,并公开用户信息,而无需每次调用服务器
import { Auth } from '../auth';
@inject(Auth)
export class AddNote {
constructor(auth) {
console.log(auth.userInfo.username); // Should return username
}
}
有关这方面的更多信息,请阅读Bluefox在您的问题评论中共享的文章。查看将用户会话数据存储在本地存储中的情况,这将解决您的问题。或者,查看这篇关于共享状态的文章-