Angular 5 两个组件共享函数和变量
Angular 5 shared function & variable among two components
我需要一个用于两个独立组件的全局函数。
我正在 HTML 主页面上使用选择器加载两个 angular 组件。
一个有功能按钮,它的功能也必须影响另一个组件中的内容。
我意识到这不容易做到...你们如何在两个 angular 组件之间设置共享函数和变量?
我正在尝试创建一个按钮,它可以在两个单独的组件中加载选项卡内容。
使用 angular 本地存储是存储某些函数和变量的解决方案吗?
提前致谢,
服务很简单。
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;
}
}
在使用公共 class 的情况下,您将获得 sharedVariable
的两个不同引用,如果您更改第一个组件中的变量值,它不会影响第二个组件,但是如果您使用 service
服务在 angular 中默认是单例的,所以您将在两个组件中获得相同的值,但只从任何地方更改值。
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;
}
}
希望对您有所帮助。
我需要一个用于两个独立组件的全局函数。 我正在 HTML 主页面上使用选择器加载两个 angular 组件。 一个有功能按钮,它的功能也必须影响另一个组件中的内容。
我意识到这不容易做到...你们如何在两个 angular 组件之间设置共享函数和变量? 我正在尝试创建一个按钮,它可以在两个单独的组件中加载选项卡内容。 使用 angular 本地存储是存储某些函数和变量的解决方案吗?
提前致谢,
服务很简单。
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;
}
}
在使用公共 class 的情况下,您将获得 sharedVariable
的两个不同引用,如果您更改第一个组件中的变量值,它不会影响第二个组件,但是如果您使用 service
服务在 angular 中默认是单例的,所以您将在两个组件中获得相同的值,但只从任何地方更改值。
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;
}
}
希望对您有所帮助。