【问题标题】:Aurelia: data is undefinedAurelia:数据未定义
【发布时间】:2017-04-04 01:19:10
【问题描述】:

我需要帮助才能从一个 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();
}

}

我尝试过使用构造函数,但现在它说 userData 是未定义的,所以它没有从第一页获取信息。我做错了什么? 谢谢!

【问题讨论】:

标签: javascript aurelia


【解决方案1】:

使用单例。在 Aurelia 中,这就像简单地创建一个类并注入它一样简单。

从我自己的一个应用程序中获取以下精简示例。

注意:这最初是 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 在您问题的 cmets 中分享的文章。

【讨论】:

    猜你喜欢
    • 2021-07-16
    • 2015-08-07
    • 2017-07-15
    • 2015-03-28
    • 1970-01-01
    • 2018-09-18
    • 1970-01-01
    • 1970-01-01
    • 2018-02-21
    相关资源
    最近更新 更多