首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >TypeError:无法读取未使用TypeDi定义的属性“”authService“”

TypeError:无法读取未使用TypeDi定义的属性“”authService“”
EN

Stack Overflow用户
提问于 2021-09-13 09:04:55
回答 1查看 136关注 0票数 0

我创建了一个类AuthRouter:

代码语言:javascript
复制
import { Router } from 'express'
import Container, { Service } from 'typedi'
import AuthenticationController from './index'

@Service()  
class AuthenticationRouter {
  constructor (private readonly authenticationController: AuthenticationController) {}

  getRouter () {
    const router = Router()
    router.get('/auth/url', this.authenticationController.getAuthUrl)

    return router
  }
}

const authRouter = Container.get(AuthenticationRouter)
const routes = authRouter.getRouter()

export default routes

AuthController.ts:

代码语言:javascript
复制
import { Request, Response } from 'express'
import { Service } from 'typedi'
import AuthenticationService from './authentication-service'

@Service()
class AuthenticationController {
  constructor (private readonly authService: AuthenticationService) {}

  async getAuthUrl (req: Request<{}, {}, {}, {redirect: string}>, res: Response) {
    return res.redirect(this.authService.generateAuthenticationUrl(req.query.redirect))
  }

  
}

export default AuthenticationController

AuthenticationService:

代码语言:javascript
复制
import { OAuth2Client } from 'google-auth-library'
import { google, oauth2_v2 } from 'googleapis'
import { Service } from 'typedi'


@Service()
class AuthenticationService {
  private oauth2Client: OAuth2Client;
  private auth: oauth2_v2.Oauth2
  constructor () {
    this.oauth2Client = new google.auth.OAuth2({
      clientId: process.env.CLIENT_ID,
      clientSecret: process.env.CLIENT_SECRET,
      redirectUri: process.env.REDIRECT_URI
    })
    this.auth = google.oauth2({
      version: 'v2',
      auth: this.oauth2Client
    })
  }

  generateAuthenticationUrl (redirect: string) {
    const url = this.oauth2Client.generateAuthUrl({
      scope: ['email', 'profile'],
      access_type: 'offline',
      state: redirect || '/'
    })
    return url
  }

}

export default AuthenticationService;

当我运行服务器时,我得到了这个错误:

代码语言:javascript
复制
(node:4470) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'authService' of undefined

我声明了authenticationRouter的容器,但我认为AuthController没有被注入。我怎么才能修复它呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-09-13 13:19:17

我更新了getRouter方法来解决这个问题:

代码语言:javascript
复制
getRouter () {
    const router = Router()
    router.get('/google/url', (req: Request<{}, {}, {}, {redirect: string}>, res) => this.authenticationController.getAuthUrl(req, res))

    return router
  }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69160021

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档