AngularDart:使用 Streams 代替 EventEmitter

AngularDart: Using Streams in leau of EventEmit

我正在将一个 angular 应用程序移植到 angulardart,我在 EventEmitter 方面遇到了一些挑战。

我目前的 .ts file 看起来像这样:

import { Component, EventEmitter } from "@angular/core";

@Component({
  selector: "app-post-create",
  templateUrl: "./post-create.component.html",
  styleUrls: ["./post-create.component.css"]
})

export class PostCreateComponent {
  enteredTitle = "";
  enteredContent = "";
  postCreated = new EventEmitter();

  onAddPost() {
    const post = {
      title: this.enteredTitle,
      content: this.enteredContent
    };
    this.postCreated.emit(post);
  }
}

根据较早的 post,

我目前的 .dart file 看起来像这样:

import 'dart:async';

import 'package:angular/angular.dart';
import 'package:angular_components/angular_components.dart';
import 'package:angular_forms/angular_forms.dart';

@Component(
  selector: 'app-post-create',
  styleUrls: ['post_create_component.css'],
  templateUrl: 'post_create_component.html',
  directives: [
    MaterialButtonComponent,
    materialInputDirectives,
    formDirectives
  ],
  providers: [],
)
class PostCreateComponent {
  String enteredTitle = '';
  String enteredContent = '';
  final _postCreatedController = new StreamController<String>();

  @Output
  Stream<String> get postCreated => _postCreatedController.stream;

  onAddPost() {
    Map<String, String> post = {
      'title': this.enteredContent,
      'content': this.enteredContent
    };
  }
}

我的 dart 文件需要修复。我没有正确使用 Stream。感谢任何帮助。

以下对我有用。您可以使用 StreamController.broadcast()。

然后您可以将您的对象添加到 add() 方法。

@Component(
  selector: 'new-post',
  directives: [coreDirectives, 
                formDirectives,
                FileUploader,
                materialInputDirectives,
                MaterialButtonComponent],
  templateUrl: 'post_new_component.html',
  styleUrls: ['post_new_component.css'],
  providers: [ClassProvider(PostService)]
)
class PostNewComponent {
  final PostService _postService;
  final _onDone = new StreamController.broadcast();

  String postText;
  Post post;

  @Input()
  Place place;

  @Output()
  Stream get doneIt => _onDone.stream;

  PostNewComponent(this._postService);

  Future<void> save() async {
    await _postService.create(postText,place.id).then(((_) => _onDone.add(1)));
  }
}

然后在 html 中您可以指定触发函数的 "doneIt" 事件。

<new-post (doneIt)="loadPosts()" [place]="place"></new-post>

在父 dart 组件文件中,您可以添加如下函数:

 Future<void> loadPosts() async {
    print("broadcast received");
  }

我认为您可以使用 loadPosts($event) 来传递事件,但这仍然需要您自己检查。

希望对您有所帮助。在这里发布了类似的问题: