SeethaPartha

SeethaPartha

  • NA
  • 89
  • 30.7k

Cannot read property , undefined in node js

Nov 30 2017 4:01 AM
his is my project with angular cli. I tried sql server as backend for my project and to configure it, I have created node server file with node js. While posting my data to Component page, it shows below error. Please check and assist me further to proceed.Thanks in advance.
Here are my codes.
 
server.js
 
var express = require('express'); // Web Framework
var app = express();
var sql = require('mssql'); // MS Sql Server client
// Connection string parameters.
var sqlConfig = {
user: 'sa',
password: 'Server@2009',
server: '172.20.10.95',
database: 'sample'
}
// Start server and listen on http://localhost:8080/
var server = app.listen(8080, function () {
var host = server.address().address
var port = server.address().port
console.log("app listening at http://%s:%s", host, port)
});
var connection = sql.connect(sqlConfig, function (err) {
if (err)
throw err;
});
module.exports = connection;
app.get('/Employee', function (req, res, err) {
var request = new sql.Request();
request.query('select * from employee', function(err, recordset) {
if(err) console.log(err);
res.end(JSON.stringify(recordset)); // Result in JSON format
});
});
 
ApiService
 
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
import { catchError, map, tap } from 'rxjs/operators';
import {Http} from '@angular/http';
import { Employee } from './Employee';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
@Injectable()
export class ApiService {
private heroesUrl = 'http://localhost:8080/Employee';
/** GET heroes from the server */
getHeroes (): Observable<Employee[]> {
return (this.http.get<Employee[]>(this.heroesUrl));
}
constructor( private http: HttpClient,
) { }
}
// @Injectable()
// export class HeroService {
// private heroesUrl = 'api/heroes'; // URL to web api
// constructor(
// private http: HttpClient,
// private messageService: MessageService) { }
// /** GET heroes from the server */
// getHeroes (): Observable<Hero[]> {
// return this.http.get<Hero[]>(this.heroesUrl)
// .pipe(
// tap(heroes => this.log(`fetched heroes`)),
// catchError(this.handleError('getHeroes', []))
// );
// }
// /** GET hero by id. Return `undefined` when id not found */
// getHeroNo404<Data>(id: number): Observable<Hero> {
// const url = `${this.heroesUrl}/?id=${id}`;
// return this.http.get<Hero[]>(url)
// .pipe(
// map(heroes => heroes[0]), // returns a {0|1} element array
// tap(h => {
// const outcome = h ? `fetched` : `did not find`;
// this.log(`${outcome} hero id=${id}`);
// }),
// catchError(this.handleError<Hero>(`getHero id=${id}`))
// );
// }
// /** GET hero by id. Will 404 if id not found */
// getHero(id: number): Observable<Hero> {
// const url = `${this.heroesUrl}/${id}`;
// return this.http.get<Hero>(url).pipe(
// tap(_ => this.log(`fetched hero id=${id}`)),
// catchError(this.handleError<Hero>(`getHero id=${id}`))
// );
// }
// /* GET heroes whose name contains search term */
// searchHeroes(term: string): Observable<Hero[]> {
// if (!term.trim()) {
// // if not search term, return empty hero array.
// return of([]);
// }
// return this.http.get<Hero[]>(`api/heroes/?name=${term}`).pipe(
// tap(_ => this.log(`found heroes matching "${term}"`)),
// catchError(this.handleError<Hero[]>('searchHeroes', []))
// );
// }
// //////// Save methods //////////
// /** POST: add a new hero to the server */
// addHero (hero: Hero): Observable<Hero> {
// return this.http.post<Hero>(this.heroesUrl, hero, httpOptions).pipe(
// tap((hero: Hero) => this.log(`added hero w/ id=${hero.id}`)),
// catchError(this.handleError<Hero>('addHero'))
// );
// }
// /** DELETE: delete the hero from the server */
// deleteHero (hero: Hero | number): Observable<Hero> {
// const id = typeof hero === 'number' ? hero : hero.id;
// const url = `${this.heroesUrl}/${id}`;
// return this.http.delete<Hero>(url, httpOptions).pipe(
// tap(_ => this.log(`deleted hero id=${id}`)),
// catchError(this.handleError<Hero>('deleteHero'))
// );
// }
// /** PUT: update the hero on the server */
// updateHero (hero: Hero): Observable<any> {
// return this.http.put(this.heroesUrl, hero, httpOptions).pipe(
// tap(_ => this.log(`updated hero id=${hero.id}`)),
// catchError(this.handleError<any>('updateHero'))
// );
// }
// /**
// * Handle Http operation that failed.
// * Let the app continue.
// * @param operation - name of the operation that failed
// * @param result - optional value to return as the observable result
// */
// private handleError<T> (operation = 'operation', result?: T) {
// return (error: any): Observable<T> => {
// // TODO: send the error to remote logging infrastructure
// console.error(error); // log to console instead
// // TODO: better job of transforming error for user consumption
// this.log(`${operation} failed: ${error.message}`);
// // Let the app keep running by returning an empty result.
// return of(result as T);
// };
// }
// /** Log a HeroService message with the MessageService */
// private log(message: string) {
// this.messageService.add('HeroService: ' + message);
// }
// }
 
Appcomponent.ts
 
import { Component } from '@angular/core';
import{HttpClient,HttpHeaders} from '@angular/common/http';
import {Http} from '@angular/http';
import { Observable} from 'rxjs/Observable';
import {Employee} from './Employee';
import { Response } from '@angular/http/src/static_response';
import { error } from 'selenium-webdriver';
import { ApiService } from './api.service';
import { catchError, map, tap } from 'rxjs/operators';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
//url:String="http://localhost:8081/Employee";
Employeedata:Employee[];
ngOnInit(){
this.getdata();
}
getdata():void{
this.apiservice.getHeroes().subscribe(res=>this.Employeedata=res);
}
constructor(private http : Http,private apiservice:ApiService){
}
}
// getHeroes(): void {
// this.heroService.getHeroes()
// .subscribe(heroes => this.heroes = heroes);
// /** GET heroes from the server */
// getHeroes (): Observable<Hero[]> {
// return this.http.get<Hero[]>(this.heroesUrl)
// .pipe(
// tap(heroes => this.log(`fetched heroes`)),
Appcomponent.html
<div>
<table>
<tr >
<td>
Id:{{Employeedata.EmpNo}}
<br/>
Name:{{Employeedata.EmpName}}
<br/>
Salary:{{Employeedata.EmpSalary}}
<br/>
Dept:{{Employeedata.EmpDept}}
<br/>
</td>
</tr>
</table>
</div>
 
 

Answers (5)