简体   繁体   中英

Angular recognize imports from root?

I have a simple service which uses 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 .

Even If I would've imported Inject, Injectable at the root module - still I had to import those in the file.

OK.

But now I'm facing a situation (code is not mine) where a developer imported some RXJS operators at the root folder :

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 :

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

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.

You can see how it is done in the RxJS source code, for example the catch operator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM