[英]Angular: data disappears on page reload
我有一个 html 模板
公司列表.component.html
<br/>
<div class="animated fadeIn">
<div class="row">
<div class="col-lg-6">
<div class="card">
<div class="card-header">
<i class="fa fa-align-justify">Employee List</i>
</div>
<div class="card-body">
<table class="table" >
<thead font-size="2px" align="center">
<tr>
<th>Id</th>
<th>Company </th>
<th>product</th>
<th>Quantity</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr align="center" *ngFor="let data of datas" >
<td>{{data.cmpid}}</td>
<td>{{data.cmpname}}</td>
<td>{{data.cmpproduct}}</td>
<td>{{data.cmpqty}}</td>
<td>{{data.cmpprice}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
单击按钮时调用的方法
公司列表.component.ts
public getCompanylist(){
console.log("getCompanyList() called");
this.datas=this.newservice.getcompanylist();
console.log(this.datas);
console.log("getcomapnylist() in companylistcomponent.ts Called da");
return this.datas;
};
在页面加载时也会调用相同的方法
公司列表.component.ts
ngOnInit() {
console.log("NG oninit called.")
this.getCompanylist();
}
getCompanylist() 反过来调用服务中的方法
myservice.ts
getcompanylist() {
alert("service method called");
this.http.get("http://localhost:8080/tabletolist").subscribe((data)=>{this.datas=data});
return this.datas;
}
当我单击按钮时, getCompanyList()
方法会按预期使用从 springboot 服务器返回的数组更新datas
字段,但在页面加载时,即使调用了相同的方法,即getCompanylist()
它将datas
字段设置为未定义,而不是从服务器返回的数据。 更奇怪的是,当组件使用路由器从另一个组件加载时,它按预期工作,但在加载相同的页面 url 时,即使调用了方法,它也会将数据字段设置为未定义。 有人请帮我弄清楚这个问题。
您可以在服务中使用 data 变量而不是返回它。
(看起来该函数可以在以原始方式完成订阅调用之前返回)。
例如:
myservice.ts
getcompanylist() {
this.http.get("http://localhost:8080/tabletolist").subscribe((data)=>{
{
this.datas=data
}
);
}
公司列表.component.ts:
ngOnInit(){
this.newservice.getcompanylist();
};
公司列表.component.html
<tr align="center" *ngFor="let data of newservice.datas" >
...
</tr>
不推荐您的编码实践,必须改进。
试试这个方法:
1-Service 应该用于服务/api 调用和数据流。
2-服务调用订阅应该在需要服务的地方处理,主要是组件而不是服务组件本身。
你的代码应该是:
myservice.ts
getCompanyList() {
const url = "http://localhost:8080/tabletolist";
return this.http.get(url);
}
公司列表.component.ts
声明任何空数组属性,即数据
public datas = [];
在组件的构造函数中初始化您的服务(private myService: myservice)
getCompanyList(){
this.myService.getCompanyList().subscribe(res => {
this.datas = res
});
}
组件初始化时调用 getCompanyList 方法
ngOnInit() {
this.getCompanyList();
}
myservice.ts
getcompanylist() {
alert("service method called");
this.http.get("http://localhost:8080/tabletolist").subscribe((data)=> data);
}
像这样尝试
公司列表.component.ts
ngOnInit() {
console.log("NG oninit called.")
this.newservice.getcompanylist().then((data) => { this.datas = data});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.