2017-04-03 83 views
0

我需要帮助才能从一个aurelia页面获取数据到另一个页面。 我做了登录页面,我问用户名和密码。然后我检查这个用户是否在数据库中。问题是,我不知道如何记住下一页中的用户名。我需要的用户名从这里:Aurelia:数据未定义

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(); 
} 

} 

我已经使用构造试过,但现在它说,用户数据是不确定的,所以它不会从第一获取信息页。我做错了什么? 谢谢!

+0

看看你的用户会话数据存储在本地存储 - 这应该解决您的问题。 – Tom

+2

或者,看看共享状态的这篇文章 - https://ilikekillnerds.com/2016/02/shared-state-in-aurelia/ – Tom

回答

0

使用单身。在奥里利亚,这很简单,只需制作一堂课并注入课程即可。

从我自己的一个应用程序中选取下面的示例。

注意:这本来就是Typescript,但我想我说得对。

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 
    } 
} 

欲了解更多信息,这篇文章thebluefox在你的问题的意见中共享的是一个很好的阅读。