0

What is the best way to access the data of an observable.

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                     

}

If I need the data stored inside to use it, how could I put it in an array?

2 Answers2

1

First define data variable as Observable only if you want to show it dynamically in the front end.!

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                     

}

In the HTML file you can simply use:

{{data.name|async}} // name or any other field defined in database

this will display the value in the HTML. Now if you want to store the value in an array you can follow this approach:

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))             
}
  • Thanks for the answer, now i can put it in the observable in the array but, How can I get only one data from the array? I need it to send it to another function – Daniel Gironás Jun 13 '20 at 20:42
0

You can define data as an observable

data: Observable<T>

Then in the subscriber ,

ngOnInit() {
 this.data = this.someService.query(this.dataID);
}           

In HTML , you can use the async pipe to subscribe to use the array

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