Home > Software design >  I used Angular12 text interpolation but the username is not displayed
I used Angular12 text interpolation but the username is not displayed

Time:02-21

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?

Useraccount.ts

eexport 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 >
<li>{{user.username}}</li>
<li><a (click)="logout($event)">logout</a></li>
</ul>

UseraccountSubject assigned to authservice.ts 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'])
     }
   )

 }


   public get useraccountValue(): Useraccount{
   return this.useraccountSubject.value;
   }
  }

Error : ERROR TypeError: Cannot read properties of null(reading 'username')

CodePudding user response:

From your code, I can see that user in useraccountSubject in Constructure of class, and its call once when you create instance. I think you have to set the value to useraccountSubject when you got the user object in login API.

You can follow this example

You can try below code, otherwise create sample project in stackbliz


    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=>{
     // Try to set After getting response from login
    tap(user => {this.useraccountSubject.next((user));})
    catchError(this.handleError)
     sessionStorage.setItem("USER", JSON.stringify(user));
     return user;
     }))
  }```

CodePudding user response:

<ng-container *ngIf="user">
<li>{{user.username}}</li>
</ng-container>

user:any= this.authservice.useraccountValue;
  • Related