首页 > 解决方案 > Angular 在哪里存储全局数据?

问题描述

我决定通过构建博客应用程序同时学习 Angular 4 和 ASP Net Core 2。我想为每个组件存储全局数据。

例如,我希望在用户登录时将记录状态传递给我的导航栏组件,这样我就可以更改按钮、显示当前用户名等。

如何从我的 LoginComponent 将数据传递给我的 NavbarComponent 等等?

标签: angular

解决方案


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


推荐阅读