Angular可观察对象指向数组,而不是订阅用户



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

(4)[{…},{…},{…},{…}]0:{时间:'Dec 14 2022 5:56PM',动作:23376089}1:{时间:'Dec 15 2022 12:02PM',动作:23139660}2:{时间:'Dec 14 2022 11:54PM',动作:23334252}3.:{时间:'Dec 15 2022 6:22AM',动作:23113578}长度:4[[原型]]:数组(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)
}
)
}

然而,当我试图打印出这个。在ngOnInit中移动,所有我得到的是控制台

下面的输出
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输入以后?

如果我理解正确,您希望从后端获取移动,将它们分配给本地变量并将它们打印到控制台。您可以通过以下代码行来实现:

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

试试这个

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

试试这个。getMoves()函数将在应用程序初始化后运行,数据将存储在'output'变量中。

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

最新更新