我对我的angular项目有一个问题。当我登录并将我用户的数据保存到本地存储,并希望与整个项目共享,以便在每个组件、模板中使用它时,无需导入UserService。你能给我一些如何解决这个问题的建议吗?谢谢。
@Injectable({
providedIn: 'root'
})
export class UserService {
// Get information of current user in local storage
getCurrentUser(): IUser {
const user = JSON.parse(localStorage.getItem('auth-user'));
return {
_id: user?._id,
avatarUrl: user?.avatarUrl,
username: user?.username,
bio: user?.bio,
};
}
}抱歉的!我的英语很差。
发布于 2021-05-25 19:16:35
您可以创建可重用的组件或指令来管理您的用户信息。
<img appAvatarUrl />
Name: <span appUserName></span>当然,这些组件必须导入UserService,但消费组件不需要知道这一点。
@Component({
selector: '[appUserName]'
template: '{{user?.name}}'
})
class UserNameComponent {
user: User;
constructor(private userService: UserService) {}
// ....
}
@Directive({
selector: '[appAvatarUrl]'
})
export class AvatarUrlDirective {
constructor(private userService: UserService, private element: ElementRef) { }
ngOnInit() {
const url = this.userService.getUser().avatarUrl;
this.element.nativeElement.setAttribute('src', url);
}
}发布于 2021-05-25 22:48:38
这是另一个你可能更喜欢的解决方案。将用户作为可观察对象添加到UserService,将服务作为公共服务注入,并使用async管道在模板中直接引用可观察对象。
export class UserService {
user$ = new BehaviourSubject<IUser>(null);
update(user: IUser) { this.user$.next(user); }
}@Component({/*...*/}) class SomeComponent {
constructor(public usr: UserService) {}
} <div>{{ (usr.user$ | async).name }}</div>
<div>{{ (usr.user$ | async).bio }}</div>
<app-some-pure-user-component [user]="usr.user$ | async" />https://stackoverflow.com/questions/67686514
复制相似问题