typescript 阵列而非用户可观察Angular

ubbxdtey  于 2022-12-19  发布在  TypeScript
关注(0)|答案(4)|浏览(128)

我想利用从API的数据,而不仅仅是打印出来。通过使用下面的代码片段,我可以显示从API的输出在控制台。

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

数据库.服务.ts

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

应用程序组件.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)
     }
       )
   }

然而,当我试图在ngOnInit中打印出这个.moves时,我得到的只是控制台中下面的输出

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

如何将移动响应保存到数组中,而不是保存到订阅者中,以便以后用作Highchart输入?

eufgjt7s

eufgjt7s1#

如果我没理解错的话,你想从后端获取移动,将它们赋值给一个局部变量,然后将它们打印到控制台。

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

w51jfk4q2#

试试这个

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);
      }),
    );
  }
cbjzeqam

cbjzeqam3#

getMoves()不是同步调用,因此您不能在ngOninit中填充输出。ngOnInt中的this.output不是this.movies。如果您在getMoves()方法中看到第二个console.log,则有一个真实的的响应。如果您尝试打印此。在ngOnInit()中直接移动:

movies = []

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

可能会打印空数组,因为调用控制台日志时响应尚未就绪。

vc6uscn9

vc6uscn94#

Try this one. getMoves() function will run once app initialized, and the data will be stored in 'output' variable.

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

相关问题