I am searching for a way to let two angular 2 apps communicate with each other. I found that I should probably make a shared service.
My main.ts
import { bootstrap } from '@angular/platform-browser-dynamic';
import { LoginComponent } from './login.component';
import { ShoppingListComponent } from './shopping-list.component';
bootstrap(LoginComponent);
bootstrap(ShoppingListComponent);
I have made a service user.service.ts
export class UserService {
authenticated: boolean;
constructor() { }
setAuthenticated(authenticated) {
this.authenticated = authenticated
}
isAutheticated() {
return this.authenticated;
}
}
Is there a way to share this service between both components?
SOLUTION
I found another way to do it with a factory:
main.ts
import { bootstrap } from '@angular/platform-browser-dynamic';
import { bind } from '@angular/core';
import { LoginComponent } from './login.component';
import { ShoppingListComponent } from './shopping-list.component';
import { UserService } from './services/user.service';
import { UserServiceFactory } from './factories/UserServiceFactory';
bootstrap(LoginComponent,[bind(UserService).toFactory(UserServiceFactory)]);
bootstrap(ShoppingListComponent,[bind(UserService).toFactory(UserServiceFactory)]);
UserServiceFactory.ts
import { UserService } from '../services/user.service';
var sdInstance = null;
export function UserServiceFactory() {
if(sdInstance == null) {
sdInstance = new UserService();
}
return sdInstance;
}
UPDATE
As said in the comments bind()
is deprecated.
main.ts
import { bootstrap } from '@angular/platform-browser-dynamic';
import { provide } from '@angular/core';
import { LoginComponent } from './login.component';
import { ShoppingListComponent } from './shopping-list.component';
import { UserService } from './services/user.service';
import { UserServiceFactory } from './factories/UserServiceFactory';
bootstrap(LoginComponent, [provide(UserService, {useFactory:UserServiceFactory})]);
bootstrap(ShoppingListComponent, [provide(UserService, {useFactory:UserServiceFactory})]);