[英]Cannot get access of stored user_id constants
我想在我的應用中調用當前用戶的個人資料。 為了做到這一點,我將用戶存儲在登錄過程中。 我將值 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
用戶服務.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);
});
}
您的 auth.service 是 Singletown 嗎?
如果 auth.service 沒有在整個應用程序中加載,在 app.module 中提供,或者在 Injector 中帶有providedIn 屬性,則當您更改頁面時,auth.service 將不會加載或將創建另一個實例。
您可以在 app.module 的 providers 屬性中提供。
providers: [ AuthService ]
帶有providedIn的示例:
@Injectable({
providedIn: 'root'
})
那示例指的是創建一個單一城鎮服務。 有很多方法可以解決這個問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.