Api调用不返回数据。 http.get()

时间:2017-01-18 06:10:05

标签: javascript api angular get

我正在尝试从API获取数据。我得到的只是204状态。我的数据库中有数据,在POSTMAN中调用时会发送正确的数据。

以下是collections.ts

ngOnInit() {
        console.log("this is collections page")

    this.loanService.getCollectionList().subscribe(response => {
          this.collections = response;
      })
    console.log(this.collections)
  }

这是我的loanService

 public getCollectionList(){
    const path = this.basePath + '/collections'; // change the path

    let queryParameters = new URLSearchParams();
    let headerParams = this.defaultHeaders;

    // queryParameters.set('','');

    let requestOptions: RequestOptionsArgs = {
        method: 'GET',
        headers: headerParams
        // search: queryParameters
    };

    return this.http.request(path, requestOptions)
        .map((response: Response)=> {
            if (response.status === 204) {
                return undefined;
            } else {
                return response.json();
            }
        });
}

这是我的路线 - collection.js

router.get('/collections', function (req, res, next) {

// var errors = req.validationErrors();

if (errors) {
    console.log('Errors');
    res.status(400);
    res.json(errors);
} else {


    console.log(req.query);

    //    db.loans.find( { 'STATE' : state, 'LOAN_BRANCH' : loanBranch },  function(err, loans ){
    db.collections.find(req.query, function (err, collections) {
        if (err) {
            res.status(400);
            res.send(err);
        } else {
            //  console.log(collections);
            res.json(collections);
        }
    })
}

});

1 个答案:

答案 0 :(得分:3)

更改

ngOnInit() {
        console.log("this is collections page")

    this.loanService.getCollectionList().subscribe(response => {
          this.collections = response;
      })
    console.log(this.collections)
  }

ngOnInit() {
        console.log("this is collections page")

    this.loanService.getCollectionList().subscribe(response => {
          this.collections = response;
          console.log(this.collections)
      })

  }

由于http调用是异步操作,因此您的响应需要一段时间才能处理。只有当响应到达回调(订阅)时才会定义this.collections

看看这篇精彩的帖子:How do I return the response from an asynchronous call?