Attempting to implement a basic login/logout feature using Angular as the frontend, I encounter an obstacle when utilizing observables. The error appears in nav.component.html:
https://i.sstatic.net/kCBDo.png
Here is the code snippet:
nav.component.ts
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { User } from '../_models/user';
import { AccountService } from '../_services/account.service';
@Component({
selector: 'app-nav',
templateUrl: './nav.component.html',
styleUrls: ['./nav.component.css']
})
export class NavComponent implements OnInit {
model : any = {};
currentUser$:Observable<User>;
constructor(private accountService : AccountService) { }
ngOnInit(): void {
this.currentUser$=this.accountService.currentUser$;
}
//corresponding codes
}
accountservice.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { ReplaySubject } from 'rxjs';
import { map } from 'rxjs/operators';
import { User } from '../_models/user';
@Injectable({
providedIn: 'root'
})
export class AccountService {
baseUrl='https://localhost:5001/api/';
private currentUserSource =new ReplaySubject<User> (1);
currentUser$=this.currentUserSource.asObservable();
constructor(private http :HttpClient) { }
login(model:any)
{
return this.http.post<User>(this.baseUrl+'account/login',model).pipe(
map((response:User)=>{
const user=response;
if(user){
localStorage.setItem('user',JSON.stringify(user));
this.currentUserSource.next(user);
}
})
)
}
setCurrentUser(user:User)
{
this.currentUserSource.next(user);
}
logout()
{
localStorage.removeItem('user');
this.currentUserSource.next(null as any);
}
}
nav.component.html
//corresponding codes
<form *ngIf="!currentUser$ | async" #loginForm="ngForm" class="d-flex" (ngSubmit)="login()" autocomplete="off">
<input
name="username"
[(ngModel)]="model.username"
class="form-control me-2"
type="text"
placeholder="username">
<input
name="password"
[(ngModel)]="model.password"
class="form-control me-2"
type="password"
placeholder="Password">
<button class="btn btn-outline-success" type="submit">LOGIN</button>
</form>
</div>
</nav>
Being new to Angular, seeking guidance on resolving this issue. Any help would be appreciated.