Subject.next未在ngOnInit中触发 [英] Subject.next not firing in ngOnInit

查看:168
本文介绍了Subject.next未在ngOnInit中触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人能解释为什么此代码(从Subject初始化值)不起作用吗?是否有错误或设计错误?我在做什么错了?

Does anyone why this code (initializing a value from Subject) does not work? Is there a bug or by design? What am I doing wrong?

ts

import { Component, OnInit } from '@angular/core';
import { Subject } from "rxjs";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.styl']
})
export class AppComponent implements OnInit {
  itemSupplier$: Subject<any[]> = new Subject<any[]>();

  items: any[] = [
    {name: 'Item 1', value: 'item1'},
    {name: 'Item 2', value: 'item2'},
  ];

  ngOnInit(){
    this.itemSupplier$.next(this.items);
  }
}

html

<ul>
    <li *ngFor="let item of itemSupplier$ | async">{{item.name}}</li>
</ul>

推荐答案

如果将其放在setTimeout中,则似乎是一个计时问题.

It seems like a timing issue, if you throw it in a setTimeout it works.

setTimeout(() => this.itemSupplier$.next(this.items), 0)

编辑

使用BehaviorSubject实际上是一个更好的主意.订阅时将提供最后一个值.

It is actually a better idea to use BehaviorSubject. This will provide the last value when it is subscribed to.

这篇关于Subject.next未在ngOnInit中触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆