Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 如何从可观测数据中获取数据并将其放入阵列中_Angular - Fatal编程技术网

Angular 如何从可观测数据中获取数据并将其放入阵列中

Angular 如何从可观测数据中获取数据并将其放入阵列中,angular,Angular,访问可观测数据的最佳方式是什么 data: DataModel[]; //this is the observable where the data is stored dataID = null; constructor(private someService: SomeService){} ngOnInit() { this.dataID = this.route.snapshot.params['id']; this.someService.query(this.dataID

访问可观测数据的最佳方式是什么

data: DataModel[]; //this is the observable where the data is stored
dataID = null;

constructor(private someService: SomeService){}

ngOnInit() {

  this.dataID = this.route.snapshot.params['id'];
  this.someService.query(this.dataID).subscribe(res => this.data = res) //here I get all the data from the observable                     

}

如果我需要存储在内存中的数据来使用它,我如何将其放入数组中?

只有在希望在前端动态显示数据变量时,才将其定义为可观察的数据变量

data: Observable;
dataID = null;

constructor(private someService: SomeService){}

ngOnInit() {

  this.dataID = this.route.snapshot.params['id'];
  this.someService.query(this.dataID).subscribe(res => this.data = res) //here I get all the data from the observable                     

}
在HTML文件中,您可以简单地使用:

{{data.name|async}} // name or any other field defined in database
这将在HTML中显示值。现在,如果要将值存储在数组中,可以采用以下方法:

dataArray: any[] = []
dataID = null;

constructor(private someService: SomeService){}

ngOnInit() {

      this.dataID = this.route.snapshot.params['id'];
      this.someService.query(this.dataID).subscribe(res =>
      this.dataArray.push(res))             
}

您可以将数据定义为可观察数据

data: Observable<T>
在HTML中,可以使用异步管道订阅以使用数组

<div *ngIf="(data | async) as myArray">
  <div *ngFor="let item of array">
  {{item.name}}
  <div>
</div>    

谢谢你的回答,现在我可以把它放在数组中的可观测数据中了,但是,我怎样才能从数组中只得到一个数据呢?我需要它发送到另一个函数
<div *ngIf="(data | async) as myArray">
  <div *ngFor="let item of array">
  {{item.name}}
  <div>
</div>