【问题标题】:Cannot get access of stored user_id constants无法访问存储的 user_id 常量
【发布时间】:2019-11-12 13:39:38
【问题描述】:

我想在我的应用中调用当前用户的个人资料。为了做到这一点,我将用户存储在登录过程中。我将值 user_id 存储在我的 auth.service 中。然后我尝试在配置文件页面中获取此键值,以显示登录的用户数据。但我真的不知道如何使用这个 ID。由于我不是来自另一个页面,我无法使用 activateRoute 逻辑。我以为我只需要调用存储然后将值存储在我的information 变量中。存储 USER_ID 的 id 是一个数字,并且存储正在工作我在那里看到我的 id。如果我想在个人资料页面中调用我的 id,我会收到 patchValue is not available for type number 的错误。

auth.service.ts

export const USER_ID = 'user_id';  
...
this.user = this.helper.decodeToken(res['access']); // the user id is stored value = 1

user.service.ts

 // get a user's profile
  getUserDetails(id: number): Observable<any> {
    return this.http.get(`${this.url}/users/${id}/`);
  }

profile.page.ts

information = null; // store my data here
id: number;  // Id to get the user data from server is a number
...

ngOnInit() {

      this.storage.get(USER_ID).then(val => { // get the stored user_id 
        this.id.patchValue({ user_id: val}); // store the current userid in id
        console.log(this.id);
      });


  // Get the information from the API
  this.userService.getUserDetails(this.id).subscribe(result => { // get the user data from the server
    this.information = result;
    console.log(result);
    console.log(this.information);
    console.log(this.id);
  });
}

【问题讨论】:

    标签: javascript angular typescript ionic-framework


    【解决方案1】:

    您的 auth.service 是 Singletown?

    如果auth.service,在整个应用程序中没有加载,在app.module中提供,或者在Injector中带有providedIn属性,当你改变页面时,auth.service将不会被加载或者会创建另一个实例。

    您可以在 app.module 中的 providers 属性中提供。

      providers: [ AuthService ]
    

    providedIn 的例子:

    @Injectable({
        providedIn: 'root'
    })
    

    那个例子是指创建一个singletown 服务。有很多方法可以解决这个问题。

    【讨论】:

    • 但这并不能解决我的问题。我已经可以使用配置文件页面中的用户名进行相同的操作(从存储中获取它,patchValue)。还有一个问题是如何使用这个 id 并获取我的数据。
    • 你的问题出在 id 属性上。因此,将 patchValue 更改为:code this.id = val; id属性是数字,不是对象,所以把数字放进去。
    • 好的,现在它丢失了`this.storage.get(USER_ID).then(val => { this.id = val; console.log(this.id); }); ` 我的控制台中的实际 ID 及其数字。但是取id的调用,id是未定义的,像那样=>http://1234/users/undefined/
    • 这个函数返回什么?在val 变量中?来一个对象?还是真实身份?如果是一个对象,你必须使用this.id = val.user_id
    • 存储的结果来自API?如果是,您的订阅必须在 then 函数中,因为 promise 是一个异步函数。尝试将 getUserDetais 放在第一个结果的 then 中。异步调用不会停止线程,因此当编译器启动 promise 时,会继续执行其余代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多