It is pretty simple with service.
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;
}
}
In the case of using a common class, you will get two different references for the sharedVariable and if you change the variable value in the first component it won't affect the second one, but if you use service the service is singleton by default in angular so you will get the same value in both components but changing the value just ones from anywhere.
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;
}
}
Hope that helps.