Angular2 API call return nothing

Viewed 57

My problem is, that it isn't displayed in html form. How can I solve this ? The query is well, and I get the result on URL, but can't display it on component.html. ( It works and I see if I call the URL /api/mainstorage so it display me the JSON content.)

Index.js

var express = require('express');
    var router = express.Router();
    // http://localhost:3000/
    router.get('/', function(req, res, next) {
        res.status(200)
          .json({
            status: 'success',
            message: 'Live long and prosper!'
          });
    });

    var db = require('./queries');  
    router.get('/api/mainstorage', db.getAllDocuments);
    module.exports = router;

Queries.js

var promise = require('bluebird');
var options = {
  // Initialization Options
  promiseLib: promise
};

var pgp = require('pg-promise')(options);
var connectionString ='postgres://dbuser:Storage@localhost/mainstorage' 
var db = pgp(connectionString);
const axios = require('axios');
const API = 'http://localhost:3000';

function getAllDocuments(req, res, next) {

  axios.get(`${API}/main`)

  db.any('SELECT * FROM files')
    .then(function (data) {
      res.status(200)
        .json({
          status: 'success',
          data: data,
          message: 'Retrieved all files'
        });
    })
    .then(documents => {
      res.send(200).json();
    })
    .catch(function (err) {
      return next(err);
    });
}

module.exports = {
    getAllDocuments: getAllDocuments
};

documents.component.ts

export class DocumentsComponent implements OnInit {
    title = 'app works!';
    mainstorage;
    documents: any [];

   constructor(private documentsService: DocumentsService) { }
      ngOnInit() {
    // Retrieve documents from the API
    this.documentsService.getAllDocuments().subscribe(documents => {
      this.documents = documents;
    });
  }
}

documents.service.ts

@Injectable()
export class DocumentsService {
   constructor(private http: Http) {}

   getAllDocuments(){
    return this.http.get('/api/mainstorage')
      .map(res => res.json());
  }
}

documents.component.html

<div class="row" *ngFor="let document of documents">
    <div class="card card-block">
      <h4 class="card-title">{{ documents.id }}</h4>
      <p class="card-text">{{document.country}}</p>
1 Answers

You are not able to see anything in the html because service data is asynchronous and you are trying to display it before the service returns it back. You can solve this by wrapping your variables in *ngIf

<div *ngIf='documnets'>
  <div class="row" *ngFor="let document of documents">
    <div class="card card-block">
      <h4 class="card-title">{{ documents.id }}</h4>
      <p class="card-text">{{document.country}}</p>
    </div>
  </div>
</div>

*ngIf will check if there are documents and once data from service is received it will be displayed.

Related