I have two angular applications in my project (app1 and app2) In app1 I have shared service:
export class SharedService {
message!:string
constructor() { }
setMessage(data:any){
this.message=data;
}
getMessage(){
return this.message;
}
}
In view1.component.ts which is located in app1 is this:
import { SharedService } from 'projects/app1/src/app/shared/shared.service';
export class View1Component implements OnInit {
constructor(private shared:SharedService) { }
message="View 1 komponenta";
ngOnInit(): void {
this.shared.setMessage(this.message);
}
}
In my app2 (this is separate application inside main folder) i have in view2.component.ts this
import { SharedService } from 'projects/app1/src/app/shared/shared.service';
export class View2Component implements OnInit {
constructor(private shared:SharedService) { }
message!:string
ngOnInit(): void {
this.message = this.shared.getMessage();
}
}
And in view2.component.html, located in app2 I want to display that data defined in app1 like this:
<p>Message ki je definiran v view1 app1: {{message}}</p>
This works, if this is in one application and sharing between components works with this exact same code (I tried it). But now, when I have 2 applications created with ng generate application app1 and app2 it doesn't work.
Main project is created by following hi
CodePudding user response:
You can move your common service in a separate NgModule
and import that module in app1
and app2
applications. For example :
import {NgModule} from '@angular/core';
import {YourCommonService} from '..common_service_path';
@NgModule({
providers: [YourCommonService]
})
export class CommonServiceModule {
// add custom logic if you want to
}
In your App1 and App2 modules, import this CommonServiceModule
:
import {NgModule} from '@angular/core';
import {CommonServiceModule} from '..common_module_path';
@NgModule({
imports: [CommonServiceModule]
})
export class YourApp1Class {
// app1 module
}
@NgModule({
imports: [CommonServiceModule]
})
export class YourApp2Class {
//app2 module
}