简体   繁体   English

静态方法中的打字稿和角度访问服务实例

[英]typescript and angular accessing service instance in a static method

I have a service which fetches the data object from the server. 我有一个从服务器获取数据对象的服务。 There is another class which is a general utility class. 还有另一个类,它是通用实用程序类。 It has a static method in which i want to use service instance. 它有一个静态方法,我想在其中使用服务实例。 but due to method being static this wont work. 但是由于方法是静态的,因此无法正常工作。 example code: 示例代码:

export class DataUtil {
    constructor(public core:CoreStructureService){

    }

    static fetchContact(id:string):ContactModel{
        for(let contact of this.core.contactList){
        if(contact.contactId == id)
            return contact
        }
    }

}

This will not compile as the line this.core.contactList in the for stmt is not valid. 这将不会编译,因为for stmt中的this.core.contactList行无效。 being method static i cannot refer core as this.core. 作为方法静态,我不能称核心为this.core。 So how do i fix this. 那么我该如何解决。

At the risk of the reputation I'm posting this as an answer. 我冒着名誉的风险将其发布为答案。

Do NOT access core service methods from a static method. 不要从static方法访问core服务方法。 This is just bad. 真不好 And this is exactly why the compiler is slapping you. 这就是编译器打您的原因。


Have your fetchContact method an instance method instead of static. 让您的fetchContact方法为实例方法,而不是静态方法。

export class DataUtil {
    constructor(public core:CoreStructureService){

    }

    fetchContact(id:string):ContactModel{
        for(let contact of this.core.contactList){
        if(contact.contactId == id)
            return contact
        }
    }

}

But... yes, you could work around it in a very dirty, half-working way. 但是...是的,您可以以一种非常肮脏,半工作的方式解决它。 I am intentionally not going to describe it. 我故意不去描述它。

But, but, but... No, you're trying to do a bad thing. 但是,但是,但是...不,您正在尝试做一件坏事。

If DataUtil was a service injected by Angular, it would not be destroyed until the corresponding injector is destroyed. 如果DataUtil是Angular注入的服务,则直到销毁相应的注入器后,它才会被销毁。 I doubt you will have performance problems because of class instantiation. 我怀疑您会因为类实例化而出现性能问题。 Try it with a regular service and only come back to this problem, if you really do have performance issues. 如果您确实有性能问题,请尝试使用常规服务,然后再回到此问题。

For further information, have a look at the Angular docs . 有关更多信息,请查看Angular文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM