Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

rxjs - Using Angular 11 AsyncPipe only show data when page initiated but missing when refresh the page

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...