【发布时间】:2017-12-13 18:02:50
【问题描述】:
考虑这段代码:
interface MyObject {
a: string,
b: string
}
@Component({
selector: 'hello',
template: `<h1>Hello {{name}}!</h1>`,
styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent implements OnInit, AfterViewInit {
@Input() name: string;
o: MyObject;
constructor(private parent: AppComponent) {
}
ngOnInit() {
this.getObject(5)
.pipe(
filter(Boolean), // removing this causes an error
catchError(err => {
console.log(err);
return Observable.empty();
})
).subscribe(obj => {
this.o = obj;
console.log(obj);
});
}
getObject(id: number): Observable<MyObject> {
if (id && typeof id !== 'undefined') {
let obj: MyObject = { a: 'x', b: 'y'};
return Observable.of(obj);
}
return Observable.empty();
}
}
getObject 方法返回 MyObject 类型的 Observable 或空的 observable。我认为当您返回一个空的 observable 时,不会调用 .subscribe,因为它会立即完成并且没有要订阅的元素。
但是,我收到一个错误:
键入'{} | MyObject' 不可分配给类型 'MyObject'。 类型“{}”不可分配给类型“MyObject”。
如果我添加过滤器(布尔值),那么错误就会消失。由于我没有执行 return Observable.of({}) 我很困惑为什么会收到此错误消息。
【问题讨论】: