使用TypeScript和Angular2下的Sequelize

4

我对Angular一无所知,现在正在学习其工作原理。希望互联网能温柔些......

我已经完成了 Angular2 的 5 分钟快速入门 和 Tour of Heroes 教程,并且没有遇到任何问题。现在我尝试连接到我的本地 MS SQL Server,因为有一个基于 SQL 的项目需要使用 Angular2 平台。我已经努力多日,但无法让 Sequelize 正常工作,真的需要帮助。

根据我读过的不同资料,我已经做了以下工作:

  • 使用 npm 安装 sequelize,并验证 sequelize 和其依赖项 lodash、bluebird 和 validator 都存在于 node_modules 中
  • 从 GitHub 的 DefinitelyTyped 项目中下载 bluebird.d.ts、lodash.d.ts、sequelize.d.ts 和 validator.d.ts 文件,并将它们放入我的 typings 文件夹中
  • 在 tsConfig.json 中,将编译器选项-->目标(target)从 es5 更改为 es6
  • 创建了一个简单的 db.component.ts 文件(见下文)
  • 更新 app.component.ts 以导入 db.component,并添加一个路由

此时简单页面已经打开,但我无法弄清如何让 Sequelize 正常工作。

我看到的脚本错误(基于使用 Visual Studio Code 作为编辑器):

  • 当我打开 sequelize.d.ts 时,有一行代码“declare module"sequelize"{”上出现错误,指出“环境模块无法嵌套其他模块”
  • 当我打开 lodash.d.ts 时,在第 239 和 240 行上(下划线处)会出现错误,指出“重复声明'_'

我尝试了很多不同的方法(猜测),但无法让 Sequelize 连接到我的数据库。我知道我需要在 db.component.ts 文件中使用 import 或 require,但最终只能得到 IDE 错误或浏览器(Chrome)中的语法错误。

我理解长期来看,我在这里测试的路由/配置等方式并不是“正确”的方法,但我只需要在重新设计之前通过基本概念验证(例如:我可以连接到数据库并查询表吗?)。

app.component.ts

import { Component }            from 'angular2/core';
import { RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from 'angular2/router';

import { DashboardComponent }   from './dashboard.component';
import { HeroService }          from './hero.service';
import { HeroesComponent }      from './heroes.component';
import { HeroDetailComponent }  from './hero-detail.component';

import { dbComponent }          from './db.component';

@Component({
    selector: 'my-app',
    template: `
        <h1>{{title}}</h1>
        <nav>
            <a [routerLink]="['Dashboard']">Dashboard</a>
            <a [routerLink]="['Heroes']">Heroes</a>
        </nav>
        <router-outlet></router-outlet>
    `,
    styleUrls: ['app/app.component.css']
    directives: [ROUTER_DIRECTIVES],
    providers: [
        ROUTER_PROVIDERS,
        HeroService
    ]
})

@RouteConfig([
    {
        path: '/dashboard',
        name: 'Dashboard',
        component: DashboardComponent,
        useAsDefault: true
    },
    {
        path: '/heroes',
        name: 'Heroes',
        component: HeroesComponent
    },
    {
        path: '/detail/:id',
        name: 'HeroDetail',
        component: HeroDetailComponent
    },
    {
        path: '/sql',
        name: 'SqlTest',
        component: dbComponent
    }   
])

export class AppComponent {
  title = 'Sample App';
}

db.component.ts

/// <reference path="../typings/sequelize.d.ts" />

import { Component, OnInit }            from 'angular2/core';
import Sequelize = require('sequelize');  <-- I dont know if this is doing anything

//- This just errors out with require not being found (tds@latest installed)
//var Sequelize = require("sequelize");

//- I know this goes somewhere, but I have no idea where
//var sql = new Sequelize('dbName', 'uName', 'pw', {
//  host: "127.0.0.1",
//  dialect: 'mssql',
//  port: 1433 <-- SqlExpress
//});

@Component({
    selector: 'my-sql',
    template:`
        <h1>SQL Test</h1>
    `
})

export class dbComponent implements OnInit {

    constructor(
    ) { }

    auth() {
        console.log('auth');
        //sql.authenticate().then(function(errors) { console.log(errors) });
    }

    ngOnInit() {
        console.log('onInit');
        this.auth();
    }
}

我的console.log信息已经能够显示,所以我相信基本功能已经实现了,但目前我不知道需要做什么来使Sequelize正常工作。

我缺少一个关键的部分,对此我感到很无助。非常感谢您提供任何帮助和指引...


请提供明确的错误信息 - Patrick Motard
@PatrickMotard:我在“脚本错误”中列出的那些可能是问题的根源,但我不确定该怎么处理它们,或者它们是否是“真正”的错误,因为它们只在IDE中显示。在db.components.ts片段中提到的“require”错误在浏览器中显示为“require未定义”。 - UncleRico
2个回答

11

首先,Sequelize 是一个 JavaScript 库。但是我无法想到在 Angular2 前端中为什么需要使用它。

要在我的“英雄之旅”Angular2应用程序中调用数据库,需要完成许多步骤。

1:你真的需要创建一个服务器,NodeJS非常棒!你可以尝试以下代码来开始:

var express = require('express');

var http = require('http');
var path = require('path');
var bodyParser = require('body-parser');
var mysql = require('ms-sql');//Note not entirely sure if this is the correct library for MS-SQL Server I would google how to use this.

var app = express();  
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));

在我们继续之前,我想指出您需要将您的Angular应用程序放在Public目录中。 您还需要获取MS-SQL库以及下载其他包,包括Express和Body-parser。 我建议先使用npm install express-generator -g ,然后进入目录并在命令行中输入express myapp

不过,我们还没有创建服务器! 接下来,我们将使其工作起来。

var server = http.createServer(app);

server.listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

然后将其放入文件中,然后在命令控制台中输入node myapp.js,您的服务器就应该运行起来了!

现在我们需要将我们的Angular2应用程序发送给它。

app.get('/', function(req, res){
    res.render('index.html');
});

这意味着查找公共文件夹中的index.html并显示它。 这是我们如何从Node启动Angular2!

现在我们的服务器已经运行起来了,让我们创建一个路由,以便我们可以从ms-sql获取应用程序的详细信息。 我要作弊,因为我不懂ms-sql,但在MySQL中,这相当容易。只需将此添加到您的同一节点文件中:

app.use(

    connection(mysql,{

        host: 'localhost',//or the IP address
        user: 'root',
        password : 'myPassword',
        port : 3306, //port mysql
        database:'myDatabaseName'
    },'request')
);

现在完成了这个步骤,我们终于可以从服务器获取数据了。

app.get('/api/heroes', function(req, res){
    req.getConnection(function(err,connection){

       connection.query("SELECT ID, ROLE_NAME, DESCRIPTION, ACTIVE_FLAG FROM ROLES",function(err,rows)     {

           if(err)
               console.log("Error Selecting : %s ",err );

           res.json({data:rows});

        });

     });
});

你会注意到我在函数调用中发送了我的行,然后用一个新名称 -> data 发送回来。

现在在 Angular2 的组件中调用它,我想要获得与之相对应的数据,我可以从 ngOnInit 中调用它。最好将其转换为服务,然后调用服务的函数,但我不会深入讨论这个问题。但你可以像这样调用它:

import { Component, OnInit }            from 'angular2/core';
import {Http} from 'angular2/http':


@Component({
    selector: 'my-sql',
    template:`
        <h1>SQL Test</h1>
         {{myData}}
    `
})

export class dbComponent implements OnInit {

    myData: any;
    constructor(public http: Http) { }


    ngOnInit() {
        this.http.get('api/heroes/').map((response => this.myData = response.json().data));
    }
}

请注意这里有很多事情正在进行。我在构造函数中实现了Http类,以便可以使用this.http来调用它!还要注意我如何导入Http类。

然后在ngOnInit中,我使用我的http类从服务器调用我的api,并将this.myData分配给response.json().data,因为记住数据是我们从服务器传回的名称?你实际上不需要添加它,只是当你接收到它时,它可能会使你的JSON更容易处理。

至于Sequelize,我不太确定它的工作原理,因为我没有使用过它,但你可以用它代替我们做MySQL的东西。

希望这能引导你朝着正确的方向前进。


太好了!这正是我所需要的。谢谢! - UncleRico

1
据我所知,Sequelize是后端的ORM。解决您的问题的方法是创建API(如果您想使用Sequelize,则可能使用Node.js),通过该API,您的前端应用程序可以进行通信。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接