如何在angular6中使用Sql服务器连接?

How to use Sql server connection in angular 6?

我已使用 sqlserver 在 'Angular6' 中建立连接。

server.js

var express = require('express');
var app = express();

app.get('/', function (req, res) {
   
    var sql = require("mssql");

    // config for your database
    var config = {
        user: 'abc',
        password: 'abc',
        server: 'servername', 
        database: 'xyz' 
    };

    // connect to your database
    sql.connect(config, function (err) {
    
        if (err) console.log(err);

        // create Request object
        var request = new sql.Request();
           
        // query to the database and get the records
        request.query('select * from tbl', function (err, recordset) {
            
            if (err) console.log(err)

            // send records as a response
            res.send(recordset);
            
        });
    });
});

var server = app.listen(5000, function () {
    console.log('Server is running..');
});

data.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class DataService {

constructor(private http: HttpClient) { }
  getUsers() {
    return this.http.get('https://jsonplaceholder.typicode.com/users')
  }
  getUser(userId) {
    return this.http.get('https://jsonplaceholder.typicode.com/users/'+userId)
  }

  getPosts() {
    return this.http.get('https://jsonplaceholder.typicode.com/posts')
  }

  getPhotos()
  {
    return this.http.get('https://jsonplaceholder.typicode.com/photos');
  }

  getTodos()
  {
    return this.http.get('https://jsonplaceholder.typicode.com/todos');
  }
}

现在我使用虚拟 API'S 作为结果。
如何让我的数据库结果投入使用? 我已成功从 Sqlserver 数据库获取结果。

我也想在我的组件中显示记录

user.component.html

<h1>Users</h1>

我可以在 user.component.ts 中导入 server.js 吗?
如果是,我该怎么做?

我觉得你误会了angular。 Angular 运行 进入浏览器,其上下文仅限于此。

如果您需要连接数据库,您需要使用一些后端技术,例如express和nodejs,如您发布的代码。

主要的方式是公开一些后端服务,比如REST服务,用服务器端技术(nodejs,j2ee,php等)开发,然后使用Angular请求他们数据。

通常要在 angular 中实现此目标,您应该使用 HttpClient

你应该搜索教程,比如 this

Angular请求数据的例子

在 angular 中你应该创建一个服务 class 来调用你公开的服务,然后在那个 class 中你可以创建一个这样的方法:

import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Observable} from 'rxjs';
import {Injectable} from '@angular/core';
import {catchError, map, tap} from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class TestService {

  get(): Observable<any> {
    return this.http.get([YOUR_BACKEND_SERVICE_URL]).pipe(
        catchError(this.handleError(`get`))
      );
  }

  private handleError<T>(operation = 'operation', result?: T) {
     return (error: any): Observable<T> => {

      console.error(error);

      this.log(`${operation} failed: ${error.message}`);

      return of(result as T);
     };
   }
}

那你应该这样写一个组件:

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {

  data: any;

  constructor(private testService: TestService) { }



  ngOnInit() {
    this.getData();
  }

  getData(): void {
    this.testService.get().subscribe(data => console.log(data));
  }

}

您需要使用 AngularCli 创建服务和组件以避免手动声明和导入它们到 app.module.ts

为了更好地理解正在发生的事情,我建议您阅读 Angular Tour of Heroes tutorial, Services section