Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 角度5共享功能&;两个组件之间的变量_Angular_Ionic Framework_Ionic2_Ionic3_Angular5 - Fatal编程技术网

Angular 角度5共享功能&;两个组件之间的变量

Angular 角度5共享功能&;两个组件之间的变量,angular,ionic-framework,ionic2,ionic3,angular5,Angular,Ionic Framework,Ionic2,Ionic3,Angular5,我需要两个独立组件的全局函数。 我在HTML主页面上使用选择器加载两个角度组件。 一个组件具有功能按钮,其功能也必须影响其他组件中的内容 我意识到这不容易做到…你们如何在两个角度分量之间设置共享函数和变量? 我试图创建一个按钮,它可以在两个单独的组件中加载选项卡内容。 使用角度局部存储是存储某些函数和变量的解决方案吗 提前感谢,服务非常简单 export class ExampleService { public sharedVariable: any; public share

我需要两个独立组件的全局函数。 我在HTML主页面上使用选择器加载两个角度组件。 一个组件具有功能按钮,其功能也必须影响其他组件中的内容

我意识到这不容易做到…你们如何在两个角度分量之间设置共享函数和变量? 我试图创建一个按钮,它可以在两个单独的组件中加载选项卡内容。 使用角度局部存储是存储某些函数和变量的解决方案吗


提前感谢,

服务非常简单

export class ExampleService {

   public sharedVariable: any;

   public sharedFunction() {
       // your implementation
   }
}


export class Component1 {
    public constructor(private service: ExampleService) {
        this.service.sharedFunction();
        this.service.sharedVariable;
    }
}

export class Component2 {
    public constructor(private service: ExampleService) {
        this.service.sharedFunction();
        this.service.sharedVariable;
    }
}
在使用公共类的情况下,
sharedVariable
将获得两个不同的引用,如果更改第一个组件中的变量值,则不会影响第二个组件,但是如果您使用
service
服务,则默认情况下角度为singleton,因此您将在两个组件中获得相同的值,但仅在任意位置更改值

export abstract class BaseClass {

   public sharedVariable: any;

   public sharedFunction() {
       // your implementation
   }
}


export class Component1 extends BaseClass {
    public constructor() {
        super();
        this.sharedFunction();
        this.sharedVariable;
    }
}

export class Component2 extends BaseClass {
    public constructor() {
        super();
        this.sharedFunction();
        this.sharedVariable;
    }
}

希望对您有所帮助。

这是一个使用Angular 5的Ionic 3项目。如果您使用的是Typescript,为什么不创建一个通用基类,组件可以从中继承?为什么不使用一个服务,将其注入到要使用共享功能的组件中?很酷,我将尝试这两种方法。如果有任何github或plunkr示例,我将不胜感激。谢谢,非常感谢,我很快就会试试这个!