How to use RxJS, MySQL and NodeJS

北城以北 提交于 2021-02-19 05:34:17

问题


I need a with RxJS for MySQL in NodeJS. Could someone give me an example for one select?

On front-end I will use Angular2.


回答1:


In my case, I'm using the MySQL npm package in a desktop application made with Electron and Angular.

However the same should work even on a plain NodeJS application by installing and importing rxjs.


I've first installed mysql and @types/mysql package with:

npm install --saved-dev mysql @types/mysql

Then I've created a MySQL service:

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();
      });
    });
  }
}

Now I can use my MysqlService in any other service or component to connect to the mysql database and execute queries.

For example:

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);
    })
  }
}


来源:https://stackoverflow.com/questions/36639493/how-to-use-rxjs-mysql-and-nodejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!