1

I have to connect in Angular 6 to SQL Server, I have used node server.js for getting data from SQL Server. When I run localhost:8887, it displays data in json format OK, but in the Angular frontend, how to get my database results in service?

serve.js

var conn = new sql.ConnectionPool({
user :'XX',
password :'XXXX',
server :'XXXXXX',
database :'XXXX',
port : 1433,
requestTimeout :300000,
options: {
  encrypt: false
}
});

app.get( "/machinedata",function ( request,response ){
 conn.connect().then(function ()
{
    var sqlQuery = "SELECT * FROM machinedata";
    var req = new sql.Request( conn );
    req.query( sqlQuery ).then(function ( recordset )
    {
        response.json( recordset.recordset );
        conn.close();
    }).catch( function ( err ) {
        conn.close();
        response.status( 400 ).send( err );
    });
    }).catch(function ( err ) {
    conn.close();
    response.status( 400 ).send( err );
    });
   });

data.service.ts

import {Injectable} from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Machinedata } from './machinedata';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

 @Injectable()

 export class DataService {
 constructor(private http: HttpClient) {}

getmachinedata() {
    return this.http.get( 'http://localhost:8887/machinedata' );
  }
 }

mdata.component.ts

   import { Component, OnInit } from '@angular/core';
   import { DataService } from '../data.service';
   import { Machinedata } from '../machinedata';

  @Component({
   selector: 'app-mdata',
   templateUrl: './mdata.component.html',
   styleUrls: ['./mdata.component.css']
   })
   export class MdataComponent implements OnInit {
    machinedatas: Machinedata[];
   constructor( private dataService: DataService) { }

    ngOnInit() {
     this.dataService.getmachinedata().subscribe((data: Machinedata[])            
     => { this.machinedatas = data;
     });
      }
Mikechen
  • 11
  • 3
  • I don't really know if that is the solution but maybe you should try to specify the whole URL. Replace `localhost:8887/machinedata` with `http://localhost:8887/machinedata` – Daniel Habenicht Sep 11 '18 at 14:51
  • thanks reply, I tried before but still don't display result – Mikechen Sep 12 '18 at 00:19
  • Do you have any errors in your Browser or while building you app? Have you debugged the service and tried to see if `this.machinedatas = data` ever gets called? – Daniel Habenicht Sep 12 '18 at 06:49
  • I've made working example from your code, you might have a look in order to spot the mistake: https://stackblitz.com/edit/angular-zhxnfs?file=src%2Fapp%2Fapp.component.ts – Daniel Habenicht Sep 12 '18 at 06:57
  • thank reply. if I save the sql json format to json file ,same like your sample. It's ok. It can read json file and display data ! But I want get from URL directly! I will try you solution later . thank u! – Mikechen Sep 12 '18 at 07:28
  • I am guessing that your http call errors for some reason. You can add an Error Callback to your subscribe function: `.subscribe((data: Machinedata[]) => { this.machinedatas = data; }, (error) => { throw new Error(error); } );` as in my example. – Daniel Habenicht Sep 12 '18 at 09:27
  • Thanks reply Daniel, I will try later. I found something difference in Jason format between my SQL query output and your sample. My SQL query output is Json array, but different format in your sample Json array. Would you give me a good advice? – Mikechen Sep 12 '18 at 22:26
  • Thanks reply Daniel. You are right, I got error message, it's http error. the error message below: " Failed to load http://192.168.0.57:8887/machinedata: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.0.57:4200' is therefore not allowed access." , How can I do next step? thank u – Mikechen Sep 13 '18 at 00:21
  • You can set the `Access-Control-Allow-Origin` Header as described in this stackoverflow: https://stackoverflow.com/a/18311469/9277073 – Daniel Habenicht Sep 13 '18 at 07:10
  • Thanks reply. I got to check my http.get result. I got a result from chrome dev tools: Failed to load resource: the server responded with a status of 404 (Not Found) Refused to execute script from '' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. I will study your sample carefully – Mikechen Sep 14 '18 at 03:11

0 Answers0