【问题标题】:Array object is not getting updated after the http service callhttp 服务调用后数组对象未更新
【发布时间】:2018-08-08 03:25:01
【问题描述】:

我正在处理一个场景,我必须使用 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。我无法遍历值。我认为数组对象存在一些更新问题。

我的服务方法是这样的,

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

springboot 应用程序完美返回对象列表,从后端没有问题。

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

【问题讨论】:

  • PRODUCTSAVINGSID 是什么?如果您在 chrome 控制台中查看 network 或其他内容,您实际上能看到任何结果吗?
  • 你应该把你的 console.log 放在订阅的返回中
  • productSavingsID 是一个 int 值,我在这里没有提到,但我在代码中提到了。是的,我在 chrome 中检查了日志语句正在打印,但它在 init 日志中始终为 0
  • @HMarteau : 那是我做的一样..

标签: angular rest typescript http


【解决方案1】:

将你的控制台移到subscribe()

ngOnInit(){

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

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

  });

}

【讨论】:

  • 我不知道这是怎么发生的,但我刚刚尝试过..它被打印出来了..问题是我需要使用 serviceSavings 中的 ID 再次调用。如果我把它嵌套在这个里面会变得很复杂..
  • @ChandraMouli 如果它没有被打印出来,这意味着你永远不会从服务中回来。而且你不再需要.map(res => res.json());
  • 相反,写这个this.serviceSavings = [...serviceSavings]查看我的答案了解更多详情
【解决方案2】:

你想在订阅完成之前得到结果,把它移到订阅里面;如果你想在视图中获取这些数据,你可以使用异步管道:

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> 

【讨论】:

    【解决方案3】:

    我有同样的确切问题,我得出的结论是应该写这个

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 2017-08-28
      相关资源
      最近更新 更多