GEVS
GEVS

Reputation: 51

angular 4 get data from database does not work

I am using angular 4 with mySql Db.

Here is my service.

service.ts

 getData(){
    return this.http.get('http://example/users.php').map(res=>{
      return res.json();
    }).catch(err=>{
      return err.json();
    })
  }

i have two pages One is Home,another one is About.

Here is my Home Component.

 ngOnInit() {
    this.API.getData().subscribe(res=>{
                console.log("dashoard",res);
    })
  }

Here is my result.

like this JSON.

[{
 "user":"name one",
 "status":"1"
},
{
 "user":"name two",
 "status":"1"
}]

I fetch records based on user status is 1.

i changed any values is database.

I changed name one user status is "0"; go to About page then click to home Page.

record length is 2.When i click ctrl+f5 record length is 1.

My problem is data retrieved.But does not get updated data.why?

I have no idea.

Kindly advice me,

Thanks.

Upvotes: 2

Views: 276

Answers (1)

Pranay Rana
Pranay Rana

Reputation: 176886

one more reason of error is , you request is inside ngOnInit method

 ngOnInit() {
    this.API.getData().subscribe(res=>{
                console.log("dashoard",res);
    })
  }

put code in Constructor

constructor() {
    this.API.getData().subscribe(res=>{
                console.log("dashoard",res);
    })
  }

service code

 getData(){
  let headers = new Headers({
            'Content-Type': 'application/json',
            'Cache-Control' : 'no-cache'
            'Access-Control-Allow-Credentials': 'true'
        });
  let options = new RequestOptions({ headers: headers });
    return this.http.get('http://example/users.php',options).map(res=>{
      return res.json();
    }).catch(err=>{
      return err.json();
    })
  }

check this also : https://fetch.spec.whatwg.org/#http-cors-protocol


Its might be because browser does caching of your data , you need to put cache to off by using Header options avaiable for Get method.

below is code for making cache off

let headers = new Headers({
   'Content-Type': 'application/json',
   'Cache-Control' : 'no-cache',
    'Access-Control-Allow-Credentials': 'true'
});
let options = new RequestOptions({ headers: headers });
return this._http.get("url", options).map(response => response.json());

Upvotes: 1

Related Questions