[英]Angular recognize imports from root?
I have a simple service which uses Inject/Injectable : 我有一个使用Inject / Injectable的简单服务:
import {Inject, Injectable} from '@angular/core';
import {APP_CONFIG} from '../../config/app-config.module';
import {AppConfig} from '../models/core/app-config.model';
@Injectable()
export class AuthService {
constructor(@Inject(APP_CONFIG) private config:AppConfig) {
}
}
Nothing new here , however -as we know - I must import Inject, Injectable
. 这里没什么新东西,但是我们知道 - 我必须导入
Inject, Injectable
。
Even If I would've imported Inject, Injectable
at the root module - still I had to import those in the file. 即使我在根模块中导入
Inject, Injectable
- 仍然我必须在文件中导入它们。
OK. 好。
But now I'm facing a situation (code is not mine) where a developer imported some RXJS operators at the root folder : 但是现在我面临的情况(代码不是我的)开发人员在根文件夹中导入了一些RXJS操作符:
rxjs-imports.ts rxjs-imports.ts
import 'rxjs/add/operator/filter'
import 'rxjs/add/operator/do'
import 'rxjs/add/operator/map'
import 'rxjs/add/operator/catch'
import 'rxjs/add/operator/shareReplay'
import 'rxjs/add/operator/distinctUntilChanged'
import 'rxjs/add/operator/pluck'
Then he imported the file in app.module.ts
: 然后他在
app.module.ts
导入了该文件:
import './rxjs-imports';
And now he can use those operator without importing them(!) at another component/service : 现在他可以使用那些运算符而无需在另一个组件/服务中导入它们(!) :
import {Observable} from 'rxjs/Observable';
//no imports for operators
public get<T>(name: string) :Observable<T>{
return this.subj.pluck( "d"); <---- how does it knows pluck ?
}
Question: 题:
I don't understand - how come it's working ? 我不明白 - 它是怎么来的? I was expected that the compiler will yell to add the
pluck
operator 我原以为编译器会大喊大叫添加
pluck
运算符
import 'rxjs/add/operator/xxx'
actually patches the Observable
prototype and extends it with the specified operators, thus importing the files ones results in being able to use those operators with every Observable
in your code from then on. import 'rxjs/add/operator/xxx'
实际上修补了Observable
原型,并使用指定的运算符对其进行扩展,因此导入文件的结果是,从那时起,您可以在代码中的每个Observable
中使用这些运算符。
You can see how it is done in the RxJS source code, for example the catch operator. 您可以在RxJS源代码中看到它是如何完成的,例如catch操作符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.