-2

If I try to call a get on my nodeJS than it's work but I get different values. I have to submit my search parameters 1-3 times to get the right output. My Node server get the right search parameter and output the right API response but if I want to print it to my Angular app then it will use a old parameters. I don't understand the behavior.

Request Path: angular -> nodeJS -> 3rd partie API -> nodeJS -> angular

Is that path wrong? how can I get the current data for angular?

APP.JS

    app.get('/url', (req, res) => {
    var name = req.query.searchname;
    console.log("Output\n---------------------------")
    console.log(req.query.searchname);
    doGetRequest(name);
    
    return res.send(data);
})

test.service

test(searchName){

    this.http.get<any>('http://localhost:3000/url', {
      params: {
        searchname: searchName
      }}).subscribe(data => this.totalAngularPackages = data)
    this.log();
    
  }

log(){
  console.log(this.totalAngularPackages);
}
Fab Ba
  • 3
  • 1

1 Answers1

0

The variable this.totalAngularPackages is assigned asynchronously. Any statements that directly depend on it must be inside the subscription. By the time the console.log is run, the variable this.totalAngularPackages is still undefined or holds the previously assigned values. You could learn more about async requests here.

test(searchName) {
  this.http.get<any>('http://localhost:3000/url', {params: {searchname: searchName}})
    .subscribe(data => {
      this.totalAngularPackages = data;
      this.log(); // <-- must be inside the subscription
    });
}

log() {
  console.log(this.totalAngularPackages);
}
ruth
  • 29,535
  • 4
  • 30
  • 57
  • I try it but it doesnt work for me. I try to output data instead of totalAngularPackages and have the same issue. – Fab Ba Oct 17 '20 at 09:52
  • I test my nodeJS server. It transmit the old data. I checked the data after the function doGetRequest and they are deprecated. Is it possible to wait until I retrieve the right data? – Fab Ba Oct 17 '20 at 10:02