我有一条指令,我想添加@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);
});
}
现在发生了什么情况,我获得了订阅的第一个值,无论该指令是成功还是错误,然后没有数据绑定到该指令。
答案 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();
});
}