Home > Net >  Angular observable to array instead of subscriber
Angular observable to array instead of subscriber

Time:12-15

I want to utilize the data from API instead of just printing it out. By using code snippets below, I can show the output from API in console.

(4) [{…}, {…}, {…}, {…}]
0
: 
{Time: 'Dec 14 2022  5:56PM', Moves: 23376089}
1
: 
{Time: 'Dec 15 2022 12:02PM', Moves: 23139660}
2
: 
{Time: 'Dec 14 2022 11:54PM', Moves: 23334252}
3
: 
{Time: 'Dec 15 2022  6:22AM', Moves: 23113578}
length
: 
4
[[Prototype]]
: 
Array(0)

database.service.ts

public getMoves(): Observable<any[]> {
    this.moves$ = this.http.get<any[]>('http://localhost:5000/api/moves');
    return this.moves$;
  }

app.component.ts

ngOnInit(): void {
    this.output = this.getMoves()
    console.log(this.output)
 
  }
getMoves() {
     return this.DataService.getMoves().subscribe((response) => {
       this.moves = response
       console.log(this.moves)
     }
       )
   }

However, when I try to print out this.moves in ngOnInit, all I get is in output below in console

SafeSubscriber {initialTeardown: undefined, closed: false, _parentage: null, _finalizers: Array(1), isStopped: false, …}
closed
: 
true
destination
: 
null
initialTeardown
: 
undefined
isStopped
: 
true
_finalizers
: 
null
_parentage
: 
null
[[Prototype]]
: 
Subscriber

How can I save moves response into an array instead of subscriber which I can use as Highchart input later?

CodePudding user response:

Try this

  ngOnInit(): void {
    this.getMoves().subscribe(response => {
      this.output = this.getMoves();
      console.log(this.output);
    });
  }
  getMoves() {
    return this.DataService.getMoves().pipe(
      tap(response => {
        this.moves = response;
        console.log(this.moves);
      }),
    );
  }

CodePudding user response:

getMoves() is not a sync call so you can not have output populate in ngOninit. this.output in ngOnInt is not this.movies. If you see the second console.log in the getMoves() method, there is a real response. If you try to print this.moves directy in ngOnInit() :

 movies = []

 ngOnInit() {
    this.getMoves();
    console.log(this.movies) //probaliy is []
 }

Probaliy will be print empty array, becasue the response is not ready yet when the console log is invoked.

  • Related