【问题标题】:How to use Sql server connection in angular 6?如何在 Angular 6 中使用 Sql 服务器连接?
【发布时间】:2018-07-19 07:19:16
【问题描述】:

我已经使用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 来获取结果。
如何让我的数据库结果投入使用? 我已成功从 Sqlserver 数据库中获取结果。

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

user.component.html

<h1>Users</h1>

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

【问题讨论】:

    标签: sql-server angular6


    【解决方案1】:

    我认为你误解了角度。 Angular 在浏览器中运行,其上下文仅限于此。

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

    主要的方式是暴露一些后端服务,比如 REST 服务,用服务器端技术(nodejs、j2ee、php 等)开发,然后使用 Angular 向它们询问数据。

    一般来说,要在 Angular 中实现这一目标,您应该使用 HttpClient

    你应该搜索一个教程,比如this

    请求数据的 Angular 示例

    在 Angular 中,您应该创建一个服务类来调用您公开的服务,然后在该类中您可以创建如下方法:

    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

    【讨论】:

    • 如果我想将此数据放入我的组件中,我该如何实现?
    • 我已经发布了我的服务,请查看。它带有假人API
    • 我不知道您在后端应用中配置了哪个网址。你应该有这样的一行: server.listen(3000, '127.0.0.1');它们是端口,最终是热名称或 IP。你只能有第一个参数,这意味着主机名的 localhost
    • 好的,所以你必须用 localhost:5000 替换你的虚拟 api URL。然后,当您添加更多 app.get() 映射时,您应该将这些 URL 添加到您的角度服务中的不同方法中。现在清楚了吗?
    • @KiranJoshi [YOUR_BACKEND_SERVICE_URL] 是您的应用程序的 json 数据的 url。 Json 文件包含来自数据库的数据,或者您可以拥有自己的数据模型。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-06
    • 1970-01-01
    • 1970-01-01
    • 2011-08-02
    • 2020-03-08
    • 1970-01-01
    相关资源
    最近更新 更多