簡體   English   中英

如何將訂閱調用中的數據分配給 Angular 中的局部變量

[英]how do i assign data from the subscribe call to a local variable in Angular

我試圖在 ngOnInit() 中聲明變量,但它超出了 scope。 我想使用該變量來迭代數據並填充我的 html 組件。 我已經在同一問題上關注了已回答的問題,但其中大多數建議在訂閱 function 中調用 function,不幸的是,在我的情況下,我只需要查看返回的數據。

import { Component, OnInit } from "@angular/core";
import { Playlist } from "../playlist";
import { PlaylistService } from "../playlist.service";

@Component({
  selector: "app-market-place",
  templateUrl: "./market-place.component.html",
  styleUrls: ["./market-place.component.css"],
})
export class MarketPlaceComponent implements OnInit {
  _playList: Playlist[] = []; //never gets assigned here

  errorMessage;
  constructor(private playListService: PlaylistService) {}

  ngOnInit() {
    this.playListService.getPlaylist().subscribe({
      next: (playList) => {
        this._playList = playList;
        console.log(this._playList); // am able to log the data but its never assigned to my _playList variable
      },
      error: (err) => (this.errorMessage = err),
    });
  }
}

我不知道您的播放列表 object 是什么樣的,但也許我有一個簡單的想法,可以解決您的問題。 我想 console.log 不能顯示你的對象數組。 您是否嘗試過以下操作?

console.log(this._playList[0]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM