我已经通过英雄之旅完成了Angular2 5分钟快速入门,并且没有任何问题.现在我正在尝试连接到我的本地MS sql服务器,因为我有一个基于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并将它们放入我的打字文件夹
>在tsConfig.json中,我更改了compilerOptions – >目标从es5到es6
>创建了一个简单的db.component.ts文件(见下文)
>更新了app.component.ts以导入db.component并添加了一个路径
此时出现了简单的页面,但我无法弄清楚如何让Sequelize工作.
我看到的脚本错误(基于使用Visual Studio Code作为我的编辑器):
>当我打开sequelize.d.ts时,“声明模块”行上有一个错误“sequelize”{‘表示“Ambient模块不能嵌套其他模块”
>当我打开lodash.d.ts时,第239行和第240行(下划线)上的错误表明“重复标识符’_”
我已经尝试了许多不同的方法(猜测)如何获得连接到我的数据库的sequelize,只是无法得到任何工作.我知道我需要(两者都是)db.component.ts文件中的import和/或require,但只会在IDE中作为错误语法或在浏览器(Chrome)中出现错误.
我明白从长远来看,我在这里测试的route / config / etc不会是“正确”的方式,但我只需要通过基本的概念验证在重新设计之前我可以对数据库做些什么(例如 – 我可以连接到数据库并查询表)
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正常运行.
有一块我不知道的谜题,我的斗智就此结束了.提前感谢任何方向……
解决方法
让我的“英雄之旅”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')));
所以在我们走得更远之前,我想指出你需要将你的角度应用程序放在公共目录中.您还需要获取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')); });
然后将其放入文件,然后在命令控制台中键入节点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',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}); }); }); });
您会注意到我正在函数调用中发送我的行,并使用新名称将其发回 – >数据.
现在在我的组件中的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().数据,因为记住数据是我们从服务器传回的名称?您实际上并不需要添加它,它可能会使您的JSON在收到时更容易处理.
至于Sequelize,我并不完全确定它是如何工作的,因为我还没有使用它,但你可以使用它代替我们如何做MysqL的东西.
希望这会引导您朝着正确的方向前进.