首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >保存随机字符串

保存随机字符串
EN

Stack Overflow用户
提问于 2018-02-26 13:37:18
回答 1查看 91关注 0票数 0

以下是我用于保存用户注册详细信息的函数:

代码语言:javascript
复制
createAdminAccount(firstName: string, lastName: string, customerEmail: string, customerMobile: string, password: string, termsAccepted: boolean, date = firebase.database.ServerValue.TIMESTAMP): Promise<any>{
return this.afAuth.auth.createUserWithEmailAndPassword(customerEmail, password)
  .then( newUser => {
    this.afDatabase.object(`/userProfile/${newUser.uid}`)
      .set({
        firstName,
        lastName,
        customerEmail,
        termsAccepted,
        customerId: newUser.uid,            
        customerAdmin: true,
        date,
        hcn: this.hcn(),
    }).then(() =>{
      ??
    })

  }, error => { console.error(error); });

}

我想保存'same‘生成的Random number以供参考。下面是我生成随机数的代码:

代码语言:javascript
复制
hcn(){
var d = new Date().getTime();
var hcNumber = 'hcn-xxxx-yxxx'.replace(/[xy]/g, function (c) {
  var r = (d + Math.random() * 16) % 16 | 0;
  d = Math.floor(d / 16);
  return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
return hcNumber;

hcn: this.hcn()的步骤生成一个随机数(在上面第一个提到的),但是当我想要保存相同的hcn: this.hcn()时,它会生成另一个随机数……我想保存与第一个循环中相同的随机数。

我想让第一个this.hcn()在全局范围内可用,以便再次使用它,并保存在单独的列表中

就是想不出来:

EN

回答 1

Stack Overflow用户

发布于 2018-02-26 13:59:02

如果你不想生成一个新的随机字符串,那么你应该只在你的应用程序中调用它一次!

在此代码片段中

代码语言:javascript
复制
//more code here
this.afDatabase.object(`/userProfile/${newUser.uid}`)
      .set({
        firstName,
        lastName,
        customerEmail,
        termsAccepted,
        customerId: newUser.uid,            
        customerAdmin: true,
        date,
        hcn: this.hcn(), <--------------
    }).then(() =>{

//more code here

不要这样做,你正在调用一个函数,从而创建一个新的随机字符串。

可能的解决方案是通过构造函数将随机字符串保存在变量中

代码语言:javascript
复制
myRandomString: string;

constructor(){
this.myRandomString = this.hcn();
}

然后在前面的代码中使用它

代码语言:javascript
复制
this.afDatabase.object(`/userProfile/${newUser.uid}`)
      .set({
        firstName,
        lastName,
        customerEmail,
        termsAccepted,
        customerId: newUser.uid,            
        customerAdmin: true,
        date,
        hcn: this.myRandomString,
    }).then(() =>{
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48982047

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档