[英]Problem with angular6 when displaying data in a component
我是 angular 的新手,我一直在開發登錄和注冊系統。 我做了登錄,一切正常,但我想顯示登錄導航欄的人的數據。 At first, I achieved this by sending the person's data that I was logging from the REST API and saving it in the localStorage and then printing it in the navbar, the problem is that when I just started a session, I got errors in the console具有未定義的名稱和角色。 為了解決這個問題,他們建議我使用 Subject,它暫時解決了我的問題,因為當我啟動 session 時,控制台中沒有錯誤,導航欄正確地向我顯示了名稱和角色,就像我注銷並啟動時一樣與新用戶。 雖然那個解決方案沒有持續多久,但我現在遇到的問題是,當我給 F5 時,一切都被破壞了,同樣的錯誤返回到控制台,好像名稱和角色不存在,不知道我該如何解決?
對不起我的英語,我正在使用翻譯:(
應用程序組件:
export class AppComponent {
public static updateUserStatus: Subject<boolean> = new Subject();
user: any;
constructor(private authService: AuthService) {
AppComponent.updateUserStatus.subscribe((res) => {
this.user = JSON.parse(localStorage.getItem("datos"));
});
}
ngOnInit() {}
}
認證服務:
signUp(user) {
return this.http
.post<any>(this.URL + "/signup", user)
.pipe(map((res) => res));
}
signIn(user): Observable<any> {
return this.http
.post<any>(this.URL + "/signin", user)
.pipe(map((res) => res));
}
登錄組件
export class SigninComponent implements OnInit {
user = {};
constructor(private authService: AuthService, private router: Router) {}
ngOnInit() {}
signIn() {
return this.authService.signIn(this.user).subscribe(
(res) => {
this.authService.setUser(res.datos);
this.authService.setToken(res.token);
/*AL ASIGNAR EL TOKEN Y EL USUARIO, LE DIGO AL APP COMPONENT QUE PUEDE
SEGUIR EJECUTANDO EL UPDATEUSERSTATUS*/
AppComponent.updateUserStatus.next(true);
this.router.navigate(["/home"]);
Swal.fire(
"Bienvenido " + res.datos.nombre_usuario,
"Tu Rol es: " + res.datos.rol,
"success"
);
},
(err) => {
Swal.fire({
icon: "error",
title: "Error",
text:
"No se ha podido iniciar sesion, verifique su correo y contraseña",
});
}
);
}
}
檢查getItem()
調用的結果(打字稿):
const settings = localStorage.getItem('key');
if (settings != null) {
this.settings = JSON.parse(settings);
}
在 html 模板中使用
user?.name
之類的東西可以安全地訪問該屬性。 ?
告訴 angular 處理未定義的用戶*ngIf
隱藏用戶信息,只要不可用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.