I'm learning Angular 11 and I got stuck with AsyncPipe, here is my code below:
Component:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AccountService } from '../_Services/_Shared/account.service';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
constructor(public accountService: AccountService, private router: Router) { }
ngOnInit(): void {
}
logout(){
this.accountService.logout();
this.router.navigateByUrl('/');
}
}
Html:
<span *ngIf="accountService.currentUser$ | async as user">{{user.UserName}}</span>
Service:
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { ReplaySubject } from 'rxjs';
import { map } from 'rxjs/operators'
import { environment } from 'src/environments/environment';
import { auth } from '../../_Models/auth';
@Injectable({
providedIn: 'root'
})
export class AccountService {
baseUrl = environment.apiUrl;
private currentUserSource = new ReplaySubject<auth>(1);
currentUser$ = this.currentUserSource.asObservable();
constructor(private http: HttpClient) { }
login(model: any){
return this.http.post<auth>(this.baseUrl + 'Login/Check_Validation_Code', model).pipe(
map((auth:auth) => {
if(auth){
this.setCurrentUser(auth);
}
}));
}
setCurrentUser(auth: auth){
localStorage.setItem('auth', JSON.stringify(auth));
this.currentUserSource.next(auth);
}
logout(){
localStorage.removeItem('auth');
this.currentUserSource.next(undefined);
}
}
The UserName is showing when the page is loaded, but when I refresh the page, it just gone
Am I missing something? or should I fix my code somewhere? please give me a hint! THX!
question from:
https://stackoverflow.com/questions/65842476/using-angular-11-asyncpipe-only-show-data-when-page-initiated-but-missing-when-r 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…