Angular 2自定义表单输入:无法读取未定义的属性“subscribe”

时间:2016-06-01 14:21:46

标签: angular

我正在尝试根据此帖Angular 2 custom form input为角度2创建文件上传的自定义表单输入 但我跟随错误错误

  

zone.js:446未处理承诺拒绝:无法读取属性   'subscribe'未定义;区域:角;任务:Promise.then;值:   TypeError:无法读取undefined(...)

的属性'subscribe'

我的代码是

import {
  Component,
  Directive,
  EventEmitter,
  Provider,
} from 'angular2/core';

import { NG_VALUE_ACCESSOR } from 'angular2/common';
import { CONST_EXPR } from 'angular2/src/facade/lang';
import { forwardRef } from 'angular2/src/core/di';

@Component({
  selector: 'file-upload',
  template: `<div
class="drop-zone"
(dragover)="dragover = true"
(dragleave)="dragover = false"
(drop)="handleFiles($event); $event.preventDefault();"
[ngClass]="{'dragover':dragover}"
>
  Drop file here
</div>
<input type="file" (change)="handleFiles($event)" id="fileup"> <label for="fileup" class="button">Upload File</label>
<br>`,
  styles: [require('./file-upload.component.sass')],
  outputs: ['fileChange'],
})
export class FileUploadComponent {
  constuctor() {
    this.fileChange = new EventEmitter(false);
  }
  setValue(value) {
    this.image = value;
  }
  handleFiles(event) {
    event.preventDefault();
    event.stopPropagation();
    const files = event.target.files || event.dataTransfer.files;
    const file = files[0];

    const reader = new FileReader();
    reader.onload = (e) => {
      this.fileChange.emit(e.target.result);
    };
    reader.readAsBinaryString(file);
  }
}

const CUSTOM_VALUE_ACCESSOR = CONST_EXPR(new Provider(
  NG_VALUE_ACCESSOR, {
    useExisting: forwardRef(() => FileUploadValueAccessor),
    multi: true,
  }));

@Directive({
  selector: 'file-upload',
  host: {
    '(fileChange)': 'onChange($event)',
  },
  providers: [CUSTOM_VALUE_ACCESSOR],
})
export class FileUploadValueAccessor {
  static get parameters() {
    return [[FileUploadComponent]];
  }
  constructor(host) {
    this.host = host;
    this.onChange = () => {};
    this.onTouched = () => {};
  }

  writeValue(value) {
    this.host.setValue(value);
  }

  registerOnChange(fn) {
    this.onChange = fn;
  }
  registerOnTouched(fn) {
    this.onTouched = fn;
  }
}

1 个答案:

答案 0 :(得分:1)

我找到了解决方案,问题是我有一个错字“constuctor”应该是“构造函数”,因此输出fileChange没有定义。