Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Sql server connection in angular 6?

I have do connection in 'Angular6' using sqlserver.

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

Right now I have used dummy API'S for result.
how to get my database results in service? I have successfully get result from Sqlserver database.

I also want to display record in my Component

user.component.html

<h1>Users</h1>

Can I have to import server.js in user.component.ts.
If yes than how can I do that?

like image 517
Kiran Joshi Avatar asked Apr 19 '26 15:04

Kiran Joshi


1 Answers

I think you are misunderstanding angular. Angular run into browser and its context is limited to that.

If you need to connect to a database, you need to use some backend technologies, like express and nodejs, as the code you posted.

The main way is to expose some backend services, like REST services, developed with a server side techonology (nodejs, j2ee, php, etc) and then use Angular to ask them for data.

Generally to achieve this goal in angular you should use HttpClient

You should search for a tutorial, like this

Angular example to request data

In angular you should create a service class to call your exposed service, then into that class you could create a method like this:

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

Then you should write a component like this:

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

}

You need to create service and component with AngularCli in order to avoid to manually declare and import them into app.module.ts

For a better understanding of what is happening I suggest you to read Angular Tour of Heroes tutorial, Services section

like image 94
firegloves Avatar answered Apr 21 '26 11:04

firegloves



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!