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?

1

2 Answers 2

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))             
}
Sign up to request clarification or add additional context in comments.

1 Comment

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
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>    

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.