'I don't see any errors in my Angular code, but when I use the developer tools, the username doesn't appear due to text interpolation errors
I don't see any errors in my Angular code, but when I use the developer tools, the username doesn't appear due to text interpolation errors.you know the answer?
authservice.ts
public get useraccountValue(): Useraccount{
return this.useraccountSubject.value; }
Useraccount.ts
export class Useraccount{
id:string ='';
username: string='';
name:string='';
password:string='';
email:string=''; }
header.ts
user= this.authservice.useraccountValue;
constructor(private authservice:AuthService) {
//this.user
this.authservice.user.subscribe(x => this.user = x);
console.log(this.user);}
header.html
<ul class="info_ul">
<li>{{user.username}}</li>
<li><a (click)="logout($event)">logout</a></li>
</ul>
UseraccountSubject assigned to authservice and BhaviorSubject Service
export class AuthService {
private useraccountSubject: BehaviorSubject<Useraccount>;
public user: Observable<Useraccount>;
constructor(private http:HttpClient, private router:Router){
this.useraccountSubject = new BehaviorSubject<Useraccount>(null as any);
this.user = this.useraccountSubject.asObservable();
if(sessionStorage.getItem("USER")){
const user =sessionStorage.getItem("USER");
if(user){
this.useraccountSubject.next(JSON.parse(user));
}
}
}
private handleError(err: HttpErrorResponse) {
if (err.status === 200) {
console.error('Error:',err.error.data)
} else {
console.error(`Backend error ${err.status}`)
}
return throwError('Try again')
}
private handleErrorsingup(err: HttpErrorResponse) {
if (err.status === 201) {
console.error('Error:',err.error.data)
} else {
alert('faild');
console.error(`Backend error ${err.status}`)
}
return throwError('Try again.')
}
login(username:string,password:string){
const params = new FormData();
params.append('username', username);
params.append('password', password);
return this.http.post<any>(`${baseUrl}/signin/`, params, {observe:'response', withCredentials: true})//withCredentials:true
.pipe(map(user=>{
catchError(this.handleError)
sessionStorage.setItem("USER", JSON.stringify(user));
return user;
}))
}
signup(email:string,password:string,name:string ){
const params = new FormData();
params.append('email', email);
params.append('password', password);
params.append('name', name);
return this.http.post<any>(`${baseUrl}/signup/`, params, {observe:'response', withCredentials: true})
.pipe(
catchError(this.handleErrorsingup)
)
}
logout(){
return this.http.post<any>(`${baseUrl}/signout/`, {}).subscribe(
response=>{
this.useraccountSubject.next(null as any)
sessionStorage.clear();
this.router.navigate(['login'])
}
)
}
isloggedIn(){
}
public get useraccountValue(): Useraccount{
return this.useraccountSubject.value;
}
}
Error : ERROR TypeError: Cannot read properties of null(reading 'username')
Solution 1:[1]
This has nothing to do with Angular.
You are trying to access a user value while is is null, without ensuring that the user exists.
This is the most common error in the large part of the most common languages.
Given you initialize your subject like so:
this.useraccountSubject = new BehaviorSubject<Useraccount>(null as any);
When a null creeps into your code you have to handle it. You have a lot of alternatives, but I', just listing two, for the sake of exposition:
<!-- 1. do not render the block it the user is null -->
<ul *ngIf="user" class="info_ul">
<li>{{user.username}}</li>
<li><a (click)="logout($event)">logout</a></li>
</ul>
<!-- 2. Make the expression null safe. I don't think it's the best for the case,
but I'm demonstrating it anyway. -->
<ul class="info_ul">
<li>{{ user != null ? user.username : '-' }}</li>
<li><a (click)="logout($event)">logout</a></li>
</ul>
I suspect that if user is null, you should not have a "logout" element anyway.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | A. Chiesa |
