在 Angular 2 的多个组件中全局持久化和访问值 [英] Persisting and accessing values globally in multiple components in Angular 2

查看:20
本文介绍了在 Angular 2 的多个组件中全局持久化和访问值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个设置页面,用户可以在其中保存一些配置变量,例如用户名.用户还可以更改该页面上的用户名.但是当我转到另一个组件(页面)并返回时,用户名没有保存.

I have a settings page where users can save some config variables, such as a Username. The user can also change the username on that page. But when I go to another Component (page) and back, the username isn't saved.

我还想在其他组件中显示用户名.我怎么做?使用全局变量?

I also want to show the username in the other components. How do I do that? With a global variable?

结构:- 应用程序- app.ts(主要)- 设置.ts- someOtherComponent.ts

Structure: - App - app.ts (main) - setting.ts - someOtherComponent.ts

推荐答案

你需要的是一个服务来维护你的变量的状态.然后,您就可以将该服务注入任何组件以设置或获取该变量.

What you need is a service to maintain the state of your variables. You would then be able to inject that service into any component to set or get that variable.

这是一个示例 (/services/my.service.ts):

Here's an example (/services/my.service.ts):

import {Injectable} from "angular2/core";

@Injectable()
export class MyService {
    private myValue;

    constructor() {}

    setValue(val) {
        this.myValue = val;
    }

    getValue() {
        return this.myValue ;
    }
}

您可能希望将该服务放入应用引导函数的 providers 数组中(可能位于主应用组件文件中,也可能位于单独的文件中,具体取决于您喜欢的操作方式).

You would probably want to put that service in the providers array of your app's bootstrap function (which might be in your main app component file, or in a separate file depending on how you like to do things).

在您的主应用文件 (/app.ts) 中:

In your main app file (/app.ts):

import {MyService} from './services/my.service';
bootstrap(App, [MyService, COMMON_DIRECTIVES, ROUTER_DIRECTIVES, ROUTER_PROVIDERS, HTTP_PROVIDERS]); // directives added here are available to all children

您不需要在数组中包含 COMMON_DIRECTIVES 和其他所有大写项目,但通常包含这些只是为了使您不必在编写的每个组件中配置它们.

You needn't have COMMON_DIRECTIVES and the other all caps items in the array, but those are commonly included just to make it so that you don't have to configure them in each component you write.

然后你会从这样的组件中访问该服务 (/components/some-component.ts):

Then you would access the service from within a component like this (/components/some-component.ts):

import {MyService} from '../services/my.service';

@Component({
    selector: 'some-component',
    template: `
<div>MyValue: {{val}}</div> 
`
})
export class SomeComponent {
    constructor(private myService:MyService) {
    }

    get val() {
        return this.myService.getValue();
    }
}

您可能还想添加到服务中,以便将值保存到某个(半)永久性的位置,以便在用户下次进入应用程序时可以访问它.

You might also want to add to the service so that it saved the value to somewhere (semi) permanent so that it could be accessed the next time the user entered the application.

这篇关于在 Angular 2 的多个组件中全局持久化和访问值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆