在node.js中,两个service不能相互调用吗?
发布于 7 年前 作者 chaoxihailing 4593 次浏览 来自 问答

这里有两个service,一个是userService,一个是GroupService,他们两个相互引用报错,是因为他们两个相互引用报错? 还是我写的格式不对? userService.pngimage.png

GroupService GroupService.png Error Error.png

7 回复

ts 完全看不懂啊

建议你去看一下require的加载机制,以及相互引用的问题,一般来说相互引用比如说a依赖b,b依赖a这种会转换为a依赖c,b依赖c

抛开代码不谈,两个模块互相调用会引起加载顺序问题,一般不会这么调用。建议看下require加载机制。

把new Service()放到class里面试试呢?

搞个抽象工厂 + 单利,每个都保存一份实例。

相互依赖会出现这样的情况,因为本身还没有运行完,所以是空的。

~/Desktop/stylus ᐅ ts-node b.ts
b
undefined
a
[Function: a]
~/Desktop/stylus ᐅ ts-node a.ts
a
undefined
b
[Function: b]

a.ts

import { Factory } from './factory'

export class a {
    name: string
    constructor() {
        this.name = "Yugo"

        let b = Factory('b');
        console.log(b);
        let b2 = Factory('b');
        console.log(b === b2);
    }
}

let assss = new a();

b.ts

export class b {
    name: string
    constructor() {
        this.name = "Yugo"
    }
}

factory.ts

import { a } from './a'
import { b } from './b'

let instace = {};

export const Factory = (className) => {
    if (instace[className]) return instace[className];
    console.dir(instace);
    switch (className) {
        case "a":
            instace[className] = new a();
            return instace[className];
        case "b":
            instace[className] = new b();
            return instace[className];
    }
}

image.png

import { a } from './a'
import { b } from './b'

let classList = {
     a,
     b
}

interface instaceType {
    a: a,
    b: b
}

let instace: instaceType = {
    a: null,
    b: null
};

type className = keyof instaceType;

export const Factory = (className: className, ...args) => {
    if (instace[className]) return instace[className];
    try{
        let currentClass = classList[className];
        if (!currentClass) throw new Error('not fond class ' + className);
        instace[className] = new currentClass()
        return instace[className];
    }catch(e){
        console.error(e)
    }
}

这个是懒汉模式,也可以自己搞一个饿汉模式。

回到顶部