Typescript 如何在Angular2中共享域模型的相同实例,并传播更改?
因此,我有一个非常简单的域模型外壳:Typescript 如何在Angular2中共享域模型的相同实例,并传播更改?,typescript,angular,Typescript,Angular,因此,我有一个非常简单的域模型外壳: import {Injectable} from 'angular2/core'; @Injectable() export class Shell { public loggedIn: boolean = false; Change(item : boolean) { this.loggedIn = item; } } 我有一个包含此属性的AppComponent: @Component({ sele
import {Injectable} from 'angular2/core';
@Injectable()
export class Shell {
public loggedIn: boolean = false;
Change(item : boolean) {
this.loggedIn = item;
}
}
我有一个包含此属性的AppComponent:
@Component({
selector: 'my-app',
providers: [TemplateRef],
templateUrl: './angular/app/Index.html',
directives: [ROUTER_DIRECTIVES, NgIf],
viewProviders: [Shell]
})
export class AppComponent {
public Shell: Shell
constructor( @Inject(Shell) _shell: any) {
this.Shell = _shell;
}
}
和索引视图的短片段:
<div *ngIf="Shell.loggedIn">
LOGGED IN!
</div>
如您所见,我尝试使用依赖项注入,但每次Shell都作为新对象返回
我真的需要制作Shell singleton吗?或者还有其他方法吗?我对angular2很陌生,所以我可能会监督一些非常基本的事情,如果我在任何地方搞砸了,请纠正我 实际上,您需要使Shell成为一个单例。您必须以提供者的身份在引导方法中添加服务。为此,您需要在引导应用程序时添加Shell服务:
bootstrap(AppComponent, [ Shell ]);
并将其从组件的所有viewProviders属性中删除:
@Component({
selector: 'my-app',
providers: [TemplateRef],
templateUrl: './angular/app/Index.html',
directives: [ROUTER_DIRECTIVES, NgIf],
// viewProviders: [Shell] <-------
})
@组件({
选择器:“我的应用程序”,
提供者:[TemplateRef],
templateUrl:'./angular/app/Index.html',
指令:[路由器指令,NgIf],
//viewProviders:[Shell]不确定传播更改是什么意思。这可能是您想要的。
@Component({
selector: 'my-app',
providers: [TemplateRef],
templateUrl: './angular/app/Index.html',
directives: [ROUTER_DIRECTIVES, NgIf],
// viewProviders: [Shell] <-------
})