hemanth koganti
hemanth koganti

Reputation: 103

Api call not returning data. http.get()

I am trying to get data from an API. All i get is a 204 status. I have data in my DB, which when called in POSTMAN sends proper data.

Here is the collections.ts:

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

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

here is my 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();
            }
        });
}

This is my route - 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);
        }
    })
}

});

Upvotes: 0

Views: 925

Answers (1)

eko
eko

Reputation: 40647

Change

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

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

to

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

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

  }

Since the http call is an async operation your response will take a while to process. Your this.collections will only be defined when the response arrives in the callback (subscribe).

Take a look this great post: How do I return the response from an asynchronous call?

Upvotes: 3

Related Questions