请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

12-27 是写这吗,这样写是想要的吗?

autowireddecortator.ts

export  function Autowired(dependencyid?: string, singleton?: boolean): MyPropDecorator {
  return (targetClassPrototype, propertyKey) => {
    let ServiceImplInstance: any
    let ServiceImplInstanceOrClass = Reflect.getMetadata("ServiceImplInstanceOrClass", targetClassPrototype, propertyKey)
    let metaSingleton = Reflect.getMetadata("singleton",
      targetClassPrototype, propertyKey)
    if (metaSingleton) {//如果是单件模式
      ServiceImplInstance = ServiceImplInstanceOrClass
    } else {
      ServiceImplInstance = new ServiceImplInstanceOrClass();
    }
    // 改了这里,直接写到class prototype上
    targetClassPrototype[`get${propertyKey as string}`] = function() {
      return ServiceImplInstance;
    }
  }
}

UserController.ts

@Controller("/")
class UserController {
  @Autowired("userServiceImpl")
  @Singleton(true)
  private userServiceImpl!: UserServiceInter 

  @get("/login")
  login(req: Request, res: Response): void { xxxx省略 }

  @post("/loginprocess")
  loginprocess(req: Request, res: Response): void {
    let session = getSession(req);

	// 从 prototyp 上拿
    const UserServiceImpl = UserController.prototype.getuserServiceImpl();
    let userinfofrmdb: Userinfo = UserServiceImpl.Login(req.body.username, req.body.pwd)
    if (userinfofrmdb && userinfofrmdb.username) { session.userinfofrmdb = userinfofrmdb }
	res.setHeader("Content-Type", "text/html;charset=UTF-8")
	let outputhtml = "";
    if (userinfofrmdb.role === "admin") {
      outputhtml += `<div>管理员:${userinfofrmdb.role}</div>`
      outputhtml += `<div><a href="/rights">进入管理员权限页面</a></div>`
    }
    res.write(outputhtml);
    res.write(`<div>登录成功,欢迎你:${userinfofrmdb.username}</div>`);
    res.write(`<div><a  href="/">进入首页</a></div>`);
    res.end();
  }
  // Dummy 接口以便上面调用不报错
  private getuserServiceImpl(): UserServiceImpl {
    return {} as UserServiceImpl
  }
}

正在回答 回答被采纳积分+3

1回答

keviny79 2023-08-17 13:41:35

不是这样写的,这是一道深度题,留给更多同学作业机会,老师就不在问答区公布答案了,需要答案参照课程2-3 的方式获取。

0 回复 有任何疑惑可以回复我~
问题已解决,确定采纳
还有疑问,暂不采纳
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号