【问题标题】:Api call not returning data. http.get()Api 调用不返回数据。 http.get()
【发布时间】:2017-06-02 10:10:29
【问题描述】:

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

这里是collections.ts

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

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

这是我的贷款服务

 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);
        }
    })
}

});

【问题讨论】:

    标签: javascript api angular get


    【解决方案1】:

    改变

    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?

    【讨论】:

    • @hemanthkoganti 取决于您如何使用它。在您的问题中包含 html。
    猜你喜欢
    • 1970-01-01
    • 2017-10-07
    • 2018-04-11
    • 2019-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-03
    相关资源
    最近更新 更多