angular - Angular 在哪里存储全局数据?
问题描述
我决定通过构建博客应用程序同时学习 Angular 4 和 ASP Net Core 2。我想为每个组件存储全局数据。
例如,我希望在用户登录时将记录状态传递给我的导航栏组件,这样我就可以更改按钮、显示当前用户名等。
如何从我的 LoginComponent 将数据传递给我的 NavbarComponent 等等?
解决方案
Stackblitz示例说明了如何通过服务在组件之间应用 observable 和 @Input 数据更改。
您将需要一个服务和带有订阅的 Rxjs 来以角度方式进行操作:
import {Injectable} from '@angular/core';
import {Subject} from 'rxjs/Subject';
@Injectable()
export class UserNameService {
execChange: Subject<any> = new Subject<any>();
constructor() {}
/**
* Use to change user name
* @data type: string
*/
userNameChange(data: string) {
this.execChange.next(data);
}
}
然后在您希望更改用户名的每个组件中添加订阅:
constructor(private userNameService : UserNameService) {
this._subscription_user_name = this.userNameService.execChange.subscribe((value) => {
this.userName= value; // this.username will hold your value and modify it every time it changes
});
}
如何更改值以便每个订阅都可以修改值?在您的服务中调用您的execChange
函数:
this.userNameService.userNameChange('Thor');
编辑:@Vikas 评论是正确的,而且非常自我解释......您需要将服务添加到 ngModule 提供程序数组,否则您会为处理未知的提供程序错误而头疼。
@NgModule({
imports: [
...
],
declarations: [...],
providers: [UserNameService]
})
如果您需要跨选项卡或刷新页面时保留数据,也可以使用localstorage
。
推荐阅读
- machine-learning - ML 模型是在所需的图像类之间还是按数据集进行分类?
- python - MSYS - PyAudio 希腊字母
- javascript - 用 Firebase 反应 Native Expo:DataSnapshot 是对象而不是数组
- python - 如何优化这段代码的运行时间?
- android - 如何在 AppGallery 上打开包含他所有应用的开发者页面
- winapi - 如何使用 CreateFile() 打开目录
- php - Laravel 5.8:接口不可实例化
- python - 如何循环遍历python中的单个元素对象列表?
- javascript - 使用多个的缺点