如何从异步功能更新HTML?

时间:2020-02-22 15:02:01

标签: angular dart angular-dart

我需要调用异步函数。通过此功能,应更新html字段。在下面的简短示例中,该名称为{{typeStream | async}}

<div class="container">
  <form>
    <mark>{{typeStream | async}}</mark>
    <hr>
    <div class="form-group">
      <input type="text" class="form-control" id="address" required placeholder="0x" #address="ngForm"
        [ngClass]="classes" ngControl="address" (ngModelChange)="setAddressCssValidityClass(address)">
    </div>
  </form>
</div>

我在Component中的最后一次尝试是以不同方式使用StreamController。但是我没有找到更新html字段{{typeStream | async}}的方法。 setAddressCssValidityClass()被正确调用,因为在模板中设置类是可行的。

这是我组件的最后一次尝试:

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

@Component(
  selector: 'validate-form',
  templateUrl: 'validate_form_component.html',
  directives: [coreDirectives, formDirectives], 
  pipes: [commonPipes],
)
class ScertValidateFormComponent {

  var classes;
  StreamController<String> typeController = StreamController<String>.broadcast();
  Stream<String> typeStream;

  Future<Null> ngOnInit() async {
    typeStream = typeController.stream;
  }

  void setAddressCssValidityClass(NgControl control) {
    var validityClass; 
    String value = control.value;
    if(value.length == 42){
      validityClass = 'is-valid';
      callByAddress(control.value);
    }
    else{
      validityClass = 'is-invalid';
    }
    Map<String, bool> map = {validityClass: true};
    classes = map;
  }

  Future<bool> callByAddress(String address) async {    
    // Some code which needs async
    typeController.add("Hello World!"); 
    return true;
  }
}

1 个答案:

答案 0 :(得分:0)

似乎您的流从未初始化。您需要实现OnInit,以便您的ngOnInit()方法将在组件生命周期中被调用,否则将永远不会执行,并且您的流仍然为空。

class ScertValidateFormComponent implements OnInit {

  var classes;
  StreamController<String> typeController = StreamController<String>.broadcast();
  Stream<String> typeStream;

  @override
  void ngOnInit() {
    typeStream = typeController.stream;
  }

  ...

但是请考虑使用这种计算的属性模式来获取流:

  StreamController<String> typeController = StreamController<String>.broadcast();
  Stream<String> get typeStream => typeController.stream;