简体   繁体   English

行为主体的访问元素

[英]Access Elements of BehaviorSubject

I am receiving an array from my data.service.ts, and want to know how to access it.我从我的 data.service.ts 接收一个数组,并想知道如何访问它。 I am currently just printing it in the console to try and understand it, however I am unsure how to do anything with the data in the array.我目前只是在控制台中打印它以尝试理解它,但是我不确定如何对数组中的数据做任何事情。

Click link below to view data format in console:点击下面的链接在控制台查看数据格式:

Observable BehaviorSubject Array Observable BehaviorSubject 数组

Inside my footer.component.ts:在我的 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);
  }

footer.component.html:页脚.component.html:

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

I am trying to access the Poster attribute of each element and display the image associated with that poster, however when I inspect the page, the src for the image is unknown: img src unknown我正在尝试访问每个元素的 Poster 属性并显示与该海报关联的图像,但是当我检查页面时,图像的 src 是未知的: img src unknown

EDIT编辑

data.service.ts数据服务.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);
  }

}

Nominations Array: Nominations Array提名数组:提名数组

If anyone knows what I am doing wrong I would appreciate it.如果有人知道我做错了什么,我将不胜感激。 New to Angular! Angular 新手!

You need to subscribe to the Observable to be notified of the values on the Subject.您需要订阅 Observable 才能收到有关主题值的通知。 An Observable notifies the subscribers of multiple values. Observable 通知订阅者多个值。 A Subject can multicast those values to many Subscribers. Subject 可以将这些值多播给许多订阅者。

You can subscribe to the Observable in the constructor of your FooterComponent like this:您可以像这样在 FooterComponent 的构造函数中订阅 Observable:

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

The callback to the subscribe method will be called with every value that is added to the subject.将使用添加到主题的每个值调用 subscribe 方法的回调。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM