可观察为指令的输入

时间:2018-12-23 13:01:50

标签: angular rxjs angular-directive

我有一条指令,我想添加@Input observable来处理可通过此指令观察到的http成功和失败的情况

Directive({
        selector: '[search]'
    })

    export class SearchDirective implements OnInit, OnChanges, OnDestroy {
    @Input() searchObs = new Subject();

ngOnInit() {
this.sub = this.searchObs.subscribe(
    data => console.log(data),
    err => console.log(err._body),
    () => console.log('directive completed')
);
}

ngOnDestroy() {
this.sub.unsubscribe();
}

ngOnChanges(changes: SimpleChanges): void {
    // tslint:disable-next-line:forin
    for (let propName in changes) {
        let change = changes[propName];
        if (propName === 'searchObs') {
            this.searchObs = (change.currentValue as Subject<any>);
                this.sub = this.searchObs.subscribe(
                    data => console.log(data),
                    err => console.log(err._body),
                    () => console.log('directive change  completed')
                );
        }
      }
  }
}

可观察到的我的组件api是

  searchObs = new Subject();
this.apiservice.getData(args).subscribe((data) => {
      this.searchObs.next(data);
    }, err => {
      this.searchObs.error(err);
    });
  }

现在发生了什么情况,我获得了订阅的第一个值,无论该指令是成功还是错误,然后没有数据绑定到该指令。

1 个答案:

答案 0 :(得分:1)

主要问题是Subject错误处理关闭了Subject上的Subject.error(),所以我在错误发生后再次重新定义了

Component.ts

this.apiservice.getData(args).subscribe((data) => {
      this.searchObs.next(data);
    }, err => {
      this.searchObs.error(err);
       this.searchObs = new Subject();
    });
  }