0

我构建了角2应用程序,我需要一种方法来获取对由角框架注入/实例化的服务/类的引用。获取我实例化的自定义类中的角2服务

我有一个通用类...让我们打电话自定义类,我使用整个网站。然而,这个类是由我实例化的,而不是角2。现在,我需要使用该类中的角2实例化的一些服务。

// this is not angular component/service 
export default class Custom { 

    constructor(properties) { 

    } 
    doSomething() { 
     // UserService is a service that is injected into other componetns constructors, but this class is not a component. 
     // Here i need a ref to the singleton 'UserService' made by angular 
     let userService = someAngularFunction.getInstance('UserService'); 
     userService.doIt(); 
    } 

} 

// in some component. 
export class MyComponent implements OnInit { 
    doAnotherThing() { 
     let c = new Custom('some generic params'); 
     c.doSomething(); 
    } 
} 
// in some n number of other components, repeat the above. 

注意,我知道我可以注入 'UserService' 到 MyComponent的,并从MyComponent的,它向下传递到新的自定义()构造。但是,由于MyComponent本身不使用该服务,并且

自定义类在很多其他地方实例化,id喜欢将该依赖项移动到Custom类中。

有没有办法做到这一点? 如果不是,最好的选择是什么。

+0

请问为什么自定义类不能是一个角度的服务呢? – DeborahK

+0

自定义类基本上是一个具有各种功能的模型,如save(),update(),sort()等。 这些模型是在服务中创建的,其中一些内容是从服务器加载的。 例如contentService会加载一个帖子列表(原始数据),并从原始数据中构建ContentModel 。然后,通过可观察订阅将这些内容模型提供给组件。 在一些组件我可以做到这一点。 。 contentService.load()订阅((个)=> { this.posts =帖子; }) 并且在一些分量函数我愿意做 this.posts [3] .save() 或在模板(点击)=“post.delete()” etc –

+0

它似乎仍然可以是一个Angular服务? – DeborahK

回答