Reputation: 3653
While following an Angular tutorial, I found this:
import 'rxjs/add/operator/switchMap';
export class HeroDetailComponent implements OnInit {
ngOnInit(): void {
this.route.paramMap
.switchMap((params: ParamMap) => this.heroService.getHero(+params.get('id')))
.subscribe(hero => this.hero = hero);
}
}
Sorry if I found this a bit strange (due to 2 reasons: I came from Java and I'm not really following latest JS technology). Isn't switchMap
a method owned by param map
which an Observable<ParamMap>
? When I remove the import statement, the code doesn't compile.
I use RxJava, but all methods required to manipulate an observable are already there (attached) with the Observable class itself.
Can someone tell me, why switchMap
import is required? Possibly, give me some reference links.
Upvotes: 0
Views: 193
Reputation: 95722
It might help you understand if you dig into the source files in your node_modules
folder. When you import switchMap
your typescript loads switchMap.d.ts
but the compiled javascript loads switchMap.js
.
switchMap.d.ts
has a declaration for interface Observable<T>
, but when you define an interface with the same name as an existing one, typescript will merge the two interface definitions. So all the import does at compile time is make the new switchMap
method accessible to anything using an Observable
:
import { switchMap } from '../../operator/switchMap';
declare module '../../Observable' {
interface Observable<T> {
switchMap: typeof switchMap;
}
}
The javascript file on the other hand modifies the prototype
for the Observable
class. This adds the new method into all instances of Observable
, so without loading this javascript the method simply doesn't exist:
"use strict";
var Observable_1 = require('../../Observable');
var switchMap_1 = require('../../operator/switchMap');
Observable_1.Observable.prototype.switchMap = switchMap_1.switchMap;
//# sourceMappingURL=switchMap.js.map
Of course you don't have to import switchMap
directly for it to be present, if any code in your program imports it then the switchMap
method will exist at runtime, but if you don't have the import
typescript will try to prevent you using it.
Upvotes: 0
Reputation: 1404
you can read this article : Where are my Observable operators
at lot of operators are missing. But this is not a fault, this is by design. Angular will not ship all available operators. This would result in additional 300 kb. So, to get an Observable with more operators, you could either import the ones you need, or import all.
when you build web application you should use less http requests, and for better performance you should compress your file size.
Upvotes: 2