gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 21:53:17 25 4
gpt4 key购买 nike

<分区>

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

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com