AngularDart:在EventEmit的leau中使用流

时间:2018-09-15 18:13:01

标签: angular angular-dart

我正在将一个角度应用程序移植到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);
  }
}

根据较早的帖子,EventEmitter is deprecated and shouldn't be used

我当前的.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。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

以下为我工作。您可以使用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)传递事件,但是您仍然需要自己进行检查。

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

How do I convert a Django QuerySet into list of dicts?