Reputation: 693
Consider this code:
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();
}
}
The method getObject returns an Observable of type MyObject or an empty observable. I thought that when you return an empty observable the .subscribe does not get called because it completes right away and there are no elements to subscribe to.
However, I get an error:
Type '{} | MyObject' is not assignable to type 'MyObject'. Type '{}' is not assignable to type 'MyObject'.
if I add the filter(Boolean) then the error goes away. Since I am not doing a return Observable.of({}) I am confused why I get this error message.
Upvotes: 0
Views: 1013
Reputation: 20043
I thought that when you return an empty observable the .subscribe does not get called because it completes right away and there are no elements to subscribe to.
It does complete right away, but subscribe
is still executed – since you execute it right away. Your next
handler will simply never be called. That's a fine distinction to make. However, this is unrelated to the issue.
However, I get an error: […]
That's a static type check from the Typescript compiler. You simply need to type your empty observable correctly:
return Observable.empty<MyObject>();
Upvotes: 1