Welcome to OStack Knowledge Sharing 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 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...