nav.component.html:
<div class="dropdown" *ngIf="currentUser$ | async" dropdown>
// some div inside
</div>
导航组件.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 {
console.log('nav.component onInit');
this.currentUser$ = this.accountService.currentUser$;
console.log(this.currentUser$);
}
}
account.service.ts:
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, 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) { }
}
我正在学习可观察的概念,并遇到了一个问题,即在没有任何数据存储在本地存储中的情况下刷新页面时,看起来我的 currentUser$ 仍然不为空。
您可能注意到,在我的 nav.component.ts 中有一个日志,每次刷新页面或删除本地存储数据时,我仍然有以下对象: