Отображение данных из Postgres в приложении Angular.Выпуск CORS - PullRequest
0 голосов
/ 28 декабря 2018

Я новый ученик и хочу отображать информацию для пользователей (в базе данных Postgres) в приложении Angular.Что у меня есть: База данных (таблица Users):

    id |   name   | age |  username   
-------+----------+----+---------------
     1 | P        | 38  | user1
     2 | Q        | 38  | user2
     3 | R        | 38  | user3

Угловой проект: server.ts:

const express = require('express'),
      cors = require('cors'),
      pg = require("pg");

const app = express();

const config = {
    user: 'appuser',
    database: 'users',
    password: '12345',
    port: 5432
  };

const pool = new pg.Pool(config);

app.get('/', (req, res, next) => {
    pool.connect(function (err, client, done) {
        if (err) {
            done();
            console.log("Can not connect to the DB" + err);
        }
        client.query('SELECT * FROM Users ORDER BY id', function (err, 
result) { 
            done();
            if (err) {
                console.log(err);
                res.status(400).send(err);
            }
            //res.status(200).send(result.rows[0]);
            return res.status(200).json(result.rows);
        })
    })
 });

app.listen(4000, function () {
    console.log('Server is running.. on Port 4000');
});

user.ts:

export interface User {
    id: number;
    name: string;
    age: number;
    username: string;
}

user.service.ts:

import { Injectable } from '@angular/core';
import { Observable, of, throwError } from 'rxjs';
import { HttpClient, HttpHeaders, HttpErrorResponse  } from 
'@angular/common/http';
import { catchError, tap, map } from 'rxjs/operators';

import { User } from './user';

const httpOptions = {
  headers: new HttpHeaders({'Content-Type': 'application/json'})
};
const apiUrl = "http://localhost:4200/api";

@Injectable({
  providedIn: 'root'
})

export class UserService {

  constructor(private http: HttpClient) { }

  getUsers (): Observable<User[]> {
    return this.http.get<User[]>(apiUrl)
      .pipe(catchError(this.handleError('getUser', [])));
  }

  getUser(id: number): Observable<User> {
    const url = `${apiUrl}/${id}`;
    return this.http.get<User>(apiUrl).pipe(
      tap(_ => console.log(`fetched User id=${id}`)),
      catchError(this.handleError<User>(`getUser id=${id}`))
    );
  }
}

user.component.ts:

import { Component, OnInit } from '@angular/core';
import { User } from '../user';
import { UserService } from '../user.service';
@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {

  users: User[];
constructor(private userService: UserService) { }

  ngOnInit() {
    this.getUsers();
}

getUsers(): void {
    this.userService.getUsers().subscribe(
    users => this.users = users);
  }

user.component.html:

<table class="table">
  <thead>
    <tr>
      <th>ID</th>
      <th>Name</th>
      <th>Age</th>
      <th>UserName</th>
    </tr>
  </thead>
  <tbody>
      <tr *ngFor="let user of users">
          <td>{{user.id}}</td>
          </a>
          <td>{{user.name}}</td>
          <td>{{user.age}}</td>
          <td>{{user.username}}</td>
      </tr>
  </tbody>
</table>

proxy.conf.json:

{
"/api": {
  "target": "http://localhost:4000",
  "secure": false,
  "pathRewrite": {
    "^/api": ""
  }
}

package.json:

...
"scripts": {
"ng": "ng",
"start": "ng serve --proxy-config proxy.conf.json",
...

При запуске "node server.ts" я могу видеть данные в http://localhost:4000, также, когда я "ng serve -o«Мое угловое приложение запущено и ошибок нет, но в таблице нет данных.Кто-нибудь может мне помочь?

...