AngularDart 5中的内部对象是Firestore + AsyncPipe吗?

时间:2018-04-18 15:14:24

标签: dart angular-dart

我一直致力于为firestore使用共享的dart包,并遇到一个有趣的问题。

我有一个业务逻辑对象基本如下:

class HomeBloc {
  final Firestore _firestore;
  CollectionReference _ref;

  HomeBloc(this._firestore) {
    _ref = _firestore.collection('test');
  }

  Stream<List<TestModel>> get results {
    return _ref.onSnapshot.asyncMap((snapshot) {
      return snapshot.docs.map((ds) => TestModel(ds.get('data') as String)).toList();
    }
  }
}

给出以下代码组件:

@Component(
  selector: 'my-app',
  templateUrl: 'app_component.html',
  directives: [coreDirectives],
  pipes: [commonPipes]
)
class AppComponent extends OnInit {
  HomeBloc bloc;
  Stream<List<TestModel>> results;

  AppComponent() {

  }

  @override
  void ngOnInit() {
    print("Initializing component");
    fb.initializeApp(
      //...
    );

    getData();
  }

  Future<void> getData() async {
    final store = fb.firestore();
    bloc = HomeBloc(store);
  }
}

我希望以下内容有效,但不会:

<div *ngIf="bloc != null">
  <h2>Loaded properly</h2>
  <ul>
    <li *ngFor="let item of bloc.results | async">
    {{item.data}}
    </li> 
  </ul>
</div>

但是,如果我将getData和html更改为以下内容:

Future<void> getData() async {
  final store = fb.firestore();
  bloc = HomeBloc(store);
  results = bloc.results;  
}

// HTML
<ul *ngFor="let item of results | async">

一切都按预期工作。这是怎么回事?

1 个答案:

答案 0 :(得分:2)

答案是get方法每次访问时都会创建一个新列表,这不会让Angular在重置前呈现项目的机会。 HomeBloc的正确实现:

class HomeBloc {
  final Firestore _firestore;
  CollectionReference _ref;

  HomeBloc(this._firestore) {
    _ref = _firestore.collection('test');
    _results = _ref.onSnapshot.asyncMap((snapshot) {
      return snapshot.docs.map((ds) => TestModel(ds.get('data') as String)).toList();
  }

  Stream<List<TestModel>> _results;
  Stream<List<TestModel>> get results => _results;
}