在http服务调用之后,Array对象没有得到更新

问题描述 投票:0回答:3

我正在研究一个场景,我必须使用rest调用从springboot中检索对象列表,并使用angular 5将它们填充到UI中。

我的组件看起来像这样,

export class BusinessComponent implements OnInit {

  serviceSavings:Services[] = [];

  constructor(private ServicesService:ServicesService) {
  }

  ngOnInit() {
    this.ServicesService.getServicesByCatID(PRODUCTSAVINGSID)
      .subscribe(serviceSavings => this.serviceSavings = serviceSavings);

    console.log("The length of serviceSavings :", this.serviceSavings.length); //this always prints zero.
  }

  examplemethod() {
    console.log("The length of serviceSavings :", this.serviceSavings.length);
  }
}

现在的问题是init()方法中的日志语句打印0行服务。我需要从列表中检索每个服务并对其执行一些操作。

我放置在用户定义的方法中的相同日志,例如在UI中使用用户操作调用它。它显示数据库表中每个列表的确切计数。

我需要在应用程序加载期间在init()中编写一些业务逻辑,以在UI中显示某些值。

但是在应用程序加载时,init()中重试列表的长度始终为0。我无法迭代价值观。我认为有一些arrayobject的更新问题。

我的服务方法看起来像这样,

  getServicesByCatID(categoryid){
    return this.http.get(this.getServiceUrlByCategory(categoryid))
      .map(res => res.json());
  }

spring boot应用程序完全返回对象列表后端没有问题。

有人可以帮我找出问题吗?

angular rest typescript http
3个回答
2
投票

将你的控制台移到subscribe()

ngOnInit(){

this.ServicesService.getServicesByCatID(PRODUCTSAVINGSID) 
.subscribe(serviceSavings => {this.serviceSavings = serviceSavings

  console.log("The length of serviceSavings :", this.serviceSavings.length)

  });

}

0
投票

您正在尝试在订阅完成之前获得结果,将其移至订阅内;如果要在视图中获取此数据,可以使用异步管道:

export class BusinessComponent implements OnInit {
 serviceSavings : Observable<Services[]>;

constructor(private ServicesService: ServicesService){}

ngOnInit(){
 this.serviceSavings = 
  this.ServicesService.getServicesByCatID(PRODUCTSAVINGSID); 
}

并且您可以在视图中迭代您的数据:

<p *ngFor='let service of serviceSavings | async'></p> 

0
投票

我有同样的问题,我得出结论,一个人应该写这个

 this.ServicesService.getServicesByCatID(PRODUCTSAVINGSID)
 .subscribe(serviceSavings => this.serviceSavings = [...serviceSavings]);

而不是this.serviceSavings = serviceSavings和相同的方式,每次你想要一个元素添加到数组,你最好写this.serviceSavings = [...serviceSavings, newServiceSaving]而不是.push(newServiceSaving)

© www.soinside.com 2019 - 2024. All rights reserved.