问题描述:Angular 7中的“Logged in user initial value is null”(登录用户的初始值为空)。
解决方法示例:
在Angular中,当我们使用一个被称为“服务”的特殊组件来管理登录用户时,有时会遇到初始值为空的问题。在这种情况下,我们可以使用RxJS的BehaviorSubject来解决这个问题。
首先,在我们的用户服务中创建一个BehaviorSubject变量来存储登录用户的信息:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class UserService {
loggedInUser$ = new BehaviorSubject(null);
constructor() { }
}
在上面的代码中,我们创建了一个名为loggedInUser$的BehaviorSubject,并将其初始值设置为null。
接下来,在登录成功后,我们可以更新loggedInUser$的值:
import { Component } from '@angular/core';
import { UserService } from './user.service';
@Component({
selector: 'app-login',
template: `
`
})
export class LoginComponent {
constructor(private userService: UserService) { }
login() {
// 登录逻辑...
// 当登录成功后,更新loggedInUser$的值
this.userService.loggedInUser$.next({ username: 'John' });
}
}
在上面的代码中,我们在登录成功后调用了userService.loggedInUser$.next()方法,将登录用户的信息传递给BehaviorSubject。
最后,在任何需要访问登录用户信息的组件中,我们可以订阅loggedInUser$来获取最新的用户信息:
import { Component, OnInit } from '@angular/core';
import { UserService } from './user.service';
@Component({
selector: 'app-profile',
template: `
Welcome, {{ user.username }}!
`
})
export class ProfileComponent implements OnInit {
loggedInUser$;
constructor(private userService: UserService) { }
ngOnInit() {
this.loggedInUser$ = this.userService.loggedInUser$;
}
}
在上面的代码中,我们使用了async管道来订阅loggedInUser$并获取最新的用户信息。
这样,在Angular 7中,“Logged in user initial value is null”问题就可以通过使用BehaviorSubject来解决了。