angular 4从数据库获取数据不起作用

时间:2017-12-01 08:14:56

标签: angular

我正在使用带有mySql Db的角度4。

这是我的服务。

service.ts

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

我有两页,一个是家,另一个是关于。

这是我的家庭组件。

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

这是我的结果。

像这样的JSON。

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

我根据用户状态获取记录为1。

我改变了任何值都是数据库。

我更改了name one用户状态为“0”; 转到“关于”页面,然后单击“主页”。

记录长度为2.当我单击ctrl + f5记录长度为1.

我的问题是检索到的数据。但是没有得到更新的数据。为什么?

我不知道。

请建议我,

感谢。

1 个答案:

答案 0 :(得分:1)

错误的另一个原因是,您请求的是ngOnInit方法

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

将代码放入构造函数

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

服务代码

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

另请检查:https://fetch.spec.whatwg.org/#http-cors-protocol

可能是因为浏览器会对您的数据进行缓存,您需要使用Header方法的Get选项将缓存设置为关闭。

下面是关闭缓存的代码

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