【问题标题】:Issues making Angular 7, Angular-Material, Node, Express, Sequelize-Typescript and Postgres work together使 Angular 7、Angular-Material、Node、Express、Sequelize-Typescript 和 Postgres 协同工作的问题
【发布时间】:2019-05-20 17:42:04
【问题描述】:

我已经使用 Angular 7 (CLI 7.3.9) 和 Angular Material 为前端、NodeJS (10.14.1)、Express (4.16.0) 和 Sequelize-Typescript (1.0.0-beta. 3)。数据库是 Postgres (4.6)。我已经创建了后端来使用 Node 和 Express 访问数据库并且可以正常工作(使用 Postman 测试)。我还使用 Sequelize-Typescript 设置了一个模型。 Angular 7 和 Material 的前端本身也可以工作。但是我在让这一切一起工作时遇到了问题,看起来它是由编译目标引起的。

我在 tsconfig.json 中尝试了不同的目标设置:“es5”和“es6”。但是当我使用 es5 时,我的后端在从 Postgres 通过 Sequelize 请求数据时会中断(请参阅下面的错误)。当我将编译目标设置为 es6 时,我的前端中断了。

tsconfig.json:

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "declaration": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "module": "commonjs",
    "moduleResolution": "node",
    "noUnusedLocals": false,
    "outDir": "./dist",
    "pretty": true,
    "sourceMap": true,
    "strictNullChecks": true,
    "strictPropertyInitialization": false,
    "target": "es6",
    "types": [
      "node"
    ],
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2018",
      "dom"
    ]
  },
  "include": [
    "src/**/*.ts",
    "index.ts"
  ],
  "exclude": [
    "node_modules"
  ]
}

从数据库请求数据时目标设置为“es5”,我在后端收到此错误:

TypeError: Class constructor Model cannot be invoked without 'new'
    at new Company (C:\Users\snleka\My Projects\hpms-ng2\src\app\server\models\Company.ts:8:42)
    at Function.build (C:\Users\snleka\My Projects\hpms-ng2\node_modules\sequelize\lib\model.js:2156:12)
    at Function.Model.(anonymous function) (C:\Users\snleka\My Projects\hpms-ng2\node_modules\sequelize-typescript\dist\model\model\model.js:116:28)

将目标设置为“es6”时,前端会出现以下错误消息:

core.js:19866 ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'nativeElement' of undefined

如何让前端和后端协同工作?

【问题讨论】:

    标签: angular postgresql express angular-material sequelize-typescript


    【解决方案1】:

    Node 依赖于 es6,但是浏览器对 es6 的支持会有所不同......您有两个选择,第一个,我建议您为前端和后端使用单独的 tsConfig。如果您不这样做,另一种选择是将您的 tsConfig 设置为 es6,但将 babel-loader 添加到您的 webpack 配置中,因此您的所有前端代码一旦被 typescript 转译到 es6,就会被转译通过 babel 到 es5。我强烈建议使用单独的 tsConfig,因为 webpack 会为前端使用 tsConfig,但后端将单独转译。

    【讨论】:

    • 我会调查的。感谢您的建议。
    • 我决定采用不同的方法并完全停止使用 Sequelize。我现在已经为 Postgres 创建了我自己的后端数据库查询,这就像一个魅力。另一个优点是我可以使用 SQL 进行复杂的查询,并且不受 Sequelize 功能的限制(如果有的话)。
    【解决方案2】:

    tsconfig.json文件中使用:

    "target": "es5",
    

    并在您的项目目录中创建一个名为.jshintrc 的新文件,并在其中写入以下内容:

     { "esversion": 6 }
    

    这对我有用。

    【讨论】:

    • 不幸的是不适合我
    猜你喜欢
    • 2021-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-12
    相关资源
    最近更新 更多