【问题标题】:Angular view not updated on new observable data角度视图未根据新的可观察数据更新
【发布时间】:2018-06-03 06:05:54
【问题描述】:

我有一个角度分量 使用这样的构造函数:

    newTrips$: Observable<Trip[]>;
    constructor(private store: Store<fromRoot.State>, private tripFeedService: TripFeedService) {
       this.newTrips$ = store.select(fromRoot.getTripFeedUnreadTrips);
       this.newTrips$.subscribe(x => { console.log('subscribe'); console.log(x); });
    }

在我看来是这样的:

<div *ngFor="let trip of newTrips$ | async">test</div>

问题是如果页面加载时 Trip[] 为空。视图中的 ngfor 永远不会被调用。我的控制台确实显示了显示“订阅”的日志消息和列表中的对象。如果刷新页面,项目就会显示出来,并且 observable 的所有后续更改都会正确显示在控制台和 ui 中

【问题讨论】:

    标签: angular


    【解决方案1】:

    由于您在ngFor 中使用了async,因此无需在构造函数中订阅 observable。

    newTrips$: Observable<Trip[]>;
        constructor(private store: Store<fromRoot.State>, private tripFeedService: TripFeedService) {
           this.newTrips$ = store.select(fromRoot.getTripFeedUnreadTrips);
        }
    

    【讨论】:

    • 构造中的订阅仅用于日志记录。
    • 最好使用 .do() 来处理日志等副作用。如果 Observable 不是多播/热的,则创建两个订阅,这可能会导致不必要的副作用。
    猜你喜欢
    • 2017-10-03
    • 1970-01-01
    • 1970-01-01
    • 2015-06-26
    • 2016-12-26
    • 2020-12-17
    • 1970-01-01
    • 2020-09-21
    • 1970-01-01
    相关资源
    最近更新 更多