Angular 2,在同一页面上运行的两个应用程序之间的通信 [英] Angular 2, communication between 2 apps running on the same page

查看:71
本文介绍了Angular 2,在同一页面上运行的两个应用程序之间的通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法,让两个有角度的2个应用程序彼此通信.我发现我应该提供共享服务.

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.

我的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;
  }
}

是否可以在两个组件之间共享此服务?

Is there a way to share this service between both components?

解决方案

我找到了另一种与工厂合作的方法:

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;
}

更新

如评论中所述,bind()已过时.

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})]);

推荐答案

简短的答案是你做不到.

The short answer is you can't.

也就是说,您可以共享一个实例,并在引导两个组件时使用它.

That being said you can share an instance and use it when bootstrapping both components.

以下是示例:

var service = new SharedService();

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

这篇关于Angular 2,在同一页面上运行的两个应用程序之间的通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆