【问题标题】:Sending an array from backend to angular 2将数组从后端发送到角度 2
【发布时间】:2018-04-24 09:37:18
【问题描述】:

我尝试使用 http.get 从后端获取一个数组。作为回应,我有:["Item1","Item2","Item3"]。

constructor(private http:Http){
    this.http.get('api').subscribe(
    data => {this.array = data}
    );
}

上面的代码使 this.array = undefined。 我应该使用什么来获取数组?

【问题讨论】:

  • 你在哪里访问this.array
  • 在构造函数中,在http.get之后
  • @user852 你检查我的答案了吗?
  • 你不能把console.log(this.array)放在http.get之后,因为它是async。你必须把它放在订阅里面

标签: arrays angular http get


【解决方案1】:

无论您是否收到data,请先尝试控制台,您还需要在subscribe之前使用.map(如果您没有使用httpClient)像这样

constructor(private http:Http){
    this.http.get('api')
.map(data => {
     console.log(data.json());
     reuturn data.json();
 )
.subscribe(data => {this.array = data});
}

【讨论】:

  • 静态数组未定义。当我 console.log(data) 我得到 "(3) ["Item1", "Item2", "Item3"] "
【解决方案2】:

您正在访问 subscribe 之外的值,因为 get 是异步的,所以您没有从中获得价值。

constructor(private http:Http){
  this.http.get('api').subscribe(
    data => {this.array = data}
    console.log(this.array); <== here it won't be undefined
  );
}

如果你想在组件中访问array,你可以使用getter

get Array() {
  return this.array;
}

在组件中你可以通过this.service.Array访问它

解决方案2

您可以使用async 管道。

【讨论】:

    猜你喜欢
    • 2023-02-23
    • 1970-01-01
    • 1970-01-01
    • 2020-05-25
    • 1970-01-01
    • 2019-01-01
    • 2020-09-17
    • 2019-07-19
    • 1970-01-01
    相关资源
    最近更新 更多