Angular 2,在同一页面上运行的2个应用程序之间的通信

时间:2016-06-03 09:50:24

标签: typescript angular

我正在寻找让两个有角度的2个应用程序相互通信的方法。我发现我应该做一个共享服务。

我的var give = 'i.want.it'; var obj = { i: { want: { it: 'Oh I know you do...' } } }; console.log(obj[give]); // 'Oh I know you do...'

main.ts

我已经提供了服务import { bootstrap } from '@angular/platform-browser-dynamic'; import { LoginComponent } from './login.component'; import { ShoppingListComponent } from './shopping-list.component'; bootstrap(LoginComponent); bootstrap(ShoppingListComponent);

user.service.ts

有没有办法在两个组件之间共享此服务?

我找到了另一种方法来处理工厂:

export class UserService { authenticated: boolean; constructor() { } setAuthenticated(authenticated) { this.authenticated = authenticated } isAutheticated() { return this.authenticated; } }

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; } 中所述,已弃用。

bind()

main.ts

1 个答案:

答案 0 :(得分:1)

简短的回答是你不能。

据说你可以共享一个实例并在引导两个组件时使用它。

以下是一个示例:

var service = new SharedService();

bootstrap(LoginComponent, [
  provide(SharedService, { useValue: service })
]);
bootstrap(ShoppingListComponent, [
  provide(SharedService, { useValue: service })
]);