2

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?

1 Answer 1

20

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

Sign up to request clarification or add additional context in comments.

8 Comments

if i want this data into my component than how can i achieve?
i have post my service please check it. its with dummy API
I don't know which url have you configured in your backend app. You should have a line like this: server.listen(3000, '127.0.0.1'); They are port and eventually hotname or ip. You could have only first param that means localhost for hostname
Ok, so you must replace your dummy api URL with localhost:5000. Then when you will add more app.get() mapping you should add these URL to different methods into your angular service. Now it's clear?
@KiranJoshi [YOUR_BACKEND_SERVICE_URL] is an url for json data of your application. Json file contain either data from database or you can have your own data model.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.