Angular2 API调用不返回任何内容

时间:2017-10-04 08:36:56

标签: node.js angular api

我的问题是,它没有以html格式显示。我怎么解决这个问题? 查询很好,我在URL上得到结果,但无法在component.html上显示。 (它有效,我看到我是否调用了URL / api / mainstorage,因此它显示了JSON内容。)

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 个答案:

答案 0 :(得分:1)

您无法在html中看到任何内容,因为服务数据是异步的,您尝试在服务返回之前显示它。 您可以通过将变量包装在*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将检查是否有documents,一旦收到服务数据,就会显示。