【发布时间】:2015-03-21 05:11:37
【问题描述】:
我需要在 2 个控制器之间共享数据。为此,正如我在 SO 上了解到的,两个控制器之间的共同合同是必要的 - 一项服务。
export interface IController1Service {
sharedItem : any;
}
class Controller1Service implements IController1Service {
sharedItem : any;
}
export class Controller1 {
constructor(contract : IController1Service) {
contract.sharedItem = "Hi Controller2!";
}
}
export class Controller2 {
constructor(contract: IController1Service) {
alert(contract.sharedItem);
}
}
现在一切正常等等。但我想知道是否真的有必要创建一个单独的服务类并将其注入两个控制器只是为了共享一个简单的变量?难道不能让 1 个控制器实现服务,然后将其注入另一个控制器吗?
export interface IController1Service {
sharedItem: any;
}
export class Controller1 implements IController1Service {
sharedItem: any;
constructor() {
this.sharedItem = "Hi Controller2!";
}
}
我试过了,但是 angular 用一个来打招呼
Can't resolve dependency for controller MyApp.Controller2 with name MyServices.IController1Service
【问题讨论】:
标签: javascript angularjs mvvm angularjs-scope typescript