在Angular中将全局数据存储在哪里? [英] Where to store global data in Angular?
问题描述
我决定通过构建博客应用程序来一次学习Angular 4和ASP Net Core 2.我到了要为每个组件存储全局数据的地步.
I decided to learn Angular 4 and ASP Net Core 2 at once by building blog application. I came to a point where I want to store global data for every component.
例如,我希望在用户登录时将登录状态传递给我的导航栏组件,这样我就可以更改按钮,显示当前用户名等.
For example, I want when the user logs in to pass the logged state to my navbar component and by that I can change the buttons, show the current user name etc.
如何通过我的LoginComponent将数据传递到NavbarComponent等?
How from my LoginComponent I can pass data to my NavbarComponent and so on?
推荐答案
Stackblitz with example of how to apply observable and @Input data changes accross components with a service.
您将需要一个服务和带有订阅的Rxjs才能以有角度的方式进行操作:
You will need a service and Rxjs with subscriptions to do it the angular way:
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);
}
}
然后在要更改用户名的每个组件中添加一个预订:
And then in every component where you want to have the user name changed add a subscription:
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
函数:
How to change the value so that every subscription can moddify the values? Call your execChange
function in your service:
this.userNameService.userNameChange('Thor');
@Vikas的评论是正确的,并且很容易解释...您需要将服务添加到ngModule provider数组中,否则您将无法解决未知的provider错误.
@Vikas comment is correct and quite self explanatory... youn need to add the service to ngModule providers array or you will get a headache dealing with unknown provider errors.
@NgModule({
imports: [
...
],
declarations: [...],
providers: [UserNameService]
})
如果您需要在标签之间或刷新页面时保留数据,请同时使用localstorage
.
If you need to persist your data across tabs or when refreshing the page, use localstorage
as well.
这篇关于在Angular中将全局数据存储在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!