我需要在NodeJS中使用RxJS for MySQL。有人可以给我一个选择的例子吗?
在前端,我将使用Angular2。
答案 0 :(得分:0)
就我而言,我在MySQL和Electron制成的桌面应用程序中使用Angular npm软件包。
通过安装和导入rxjs,即使在普通的NodeJS应用程序上也可以使用。
我首先使用以下程序安装了mysql
和@types/mysql
软件包:
npm install --saved-dev mysql @types/mysql
然后我创建了一个MySQL服务:
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Connection, ConnectionConfig, FieldInfo, MysqlError } from 'mysql';
const mysql = require('mysql');
@Injectable({
providedIn: 'root'
})
export class MysqlService {
private connection: Connection;
constructor() { }
createConnection(config: ConnectionConfig) {
this.connection = mysql.createConnection(config);
}
query(queryString: string, values?: string[]): Observable<{results?: Object[], fields?: FieldInfo[]}> {
return new Observable(observer => {
this.connection.query(queryString, values, (err: MysqlError, results?: Object[], fields?: FieldInfo[]) => {
if (err) {
observer.error(err);
} else {
observer.next({ results, fields });
}
observer.complete();
});
});
}
}
现在,我可以在任何其他服务或组件中使用MysqlService
连接到mysql数据库并执行查询。
例如:
import { Component, OnInit } from '@angular/core';
import { MysqlService } from '../../services/mysql.service';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
constructor(
private mysqlService: MysqlService,
) { }
ngOnInit() {
this.mysqlService.createConnection({
host: '127.0.0.1',
user: 'root',
password: 'my_password',
database: 'my_database',
});
this.mysqlService.query(`SELECT * FROM my_table WHERE name = 'Francesco'`).subscribe((data) => {
console.log(data);
})
}
}