首页 > 解决方案 > 行为主体的访问元素

问题描述

我从我的 data.service.ts 接收一个数组,并想知道如何访问它。我目前只是在控制台中打印它以尝试理解它,但是我不确定如何对数组中的数据做任何事情。

点击下面的链接在控制台查看数据格式:

Observable BehaviorSubject 数组

在我的 footer.component.ts 里面:

import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';

@Component({
  selector: 'app-footer',
  templateUrl: './footer.component.html',
  styleUrls: ['./footer.component.css']
})
export class FooterComponent {

  nominations = [];

  constructor(private dataService: DataService) { 
    this.nominations.push(this.dataService.currentNoms);
  }

页脚.component.html:

<div id="podiums" *ngFor="let nom of nominations">
    <img src="{{nom.Poster}}">
</div>

我正在尝试访问每个元素的 Poster 属性并显示与该海报关联的图像,但是当我检查页面时,图像的 src 是未知的: img src unknown

编辑

数据服务.ts

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class DataService {

  private finalNoms = new BehaviorSubject<any>([]);
  currentNoms = this.finalNoms.asObservable();

  constructor() { }

  addNominations(nom: Object){
    this.finalNoms.next(nom);
  }

}

提名数组: 提名数组

如果有人知道我做错了什么,我将不胜感激。Angular 新手!

标签: angulartypescriptangular-components

解决方案


您需要订阅 Observable 才能收到有关主题值的通知。Observable 通知订阅者多个值。Subject 可以将这些值多播给许多订阅者。

您可以像这样在 FooterComponent 的构造函数中订阅 Observable:

constructor(private dataService: DataService) { 
  this.dataService.currentNoms.subscribe(noms => {
    this.nominations.push(noms);
  });

将使用添加到主题的每个值调用 subscribe 方法的回调。


推荐阅读