×
  • Best Way To Build And Publish Angular Library (v10)

  • 02 – Making Configurable Library Module

    Lesson List

    In this lesson, we will go through how can we create a configurable Library Module. for example, in this course, we are making a library that displays the news from some external API but the API must have a token.
    as we are creating a library that will be available globally via NPM package manager, so for that we have to accept the token from the user end.

    Configurable Library Module

    Already we have generated the library folder using angular CLI, now the first thing will do is create an Injection service that will accept the token from the user’s app module.
    so in our library folder inside src/lib/ will create a file named as api-config.ts

    src/lib/api-config.ts
    
    import { InjectionToken } from '@angular/core';
    export interface NewsConfig {
      Token: string;
    }
    export const NewsTwentyfourConfigService = new InjectionToken<NewsConfig>('NewsConfig');
    

    know more about InjectionToken
    The next thing are we going to do is we will use this Token from NewsTwentyfourConfigService in our library module.

    src/lib/news-twentyfour.module.ts
    
    @NgModule({
      declarations: [NewsTwentyfourComponent],
      imports: [HttpClientModule, CommonModule],
      exports: [NewsTwentyfourComponent] // must be exported to use in other Module
    })
    export class NewsTwentyfourModule {
      // here goes a forRoot() static method in our module which takes the object and provides it.
    }
    

    The forRoot() static method will return ModuleWithProviders which will contain the NewsTwentyfourConfigService

    src/lib/news-twentyfour.module.ts
    
    @NgModule({...})
    export class NewsTwentyfourModule {
      static forRoot(config: NewsConfig): ModuleWithProviders {
        return {
          ngModule: NewsTwentyfourModule,
          providers: [
            NewsTwentyfourService, // service for news API
            { provide: NewsTwentyfourConfigService, useValue: config } // service for configuring token in API
          ]
        };
      }
    }
    

    so where ever you import the module you can pass the token inside it for example.

    app.module.ts
    
    @NgModule({
      ...
      imports: [
        NewsTwentyfourModule.forRoot({Token: 'xxxxxx-xxxxx-xxx-xxxxx-xxxxxxxx'})
      ]
      ...
    })
    

    Using Config Value In Service

    Till now we have created a configurable Library Module but for using those values we have to also inject the service i.e. NewsTwentyfourConfigService into the service file.
    For this course we have use gnews.io API

    src/lib/news-twentyfour.service.ts
    
    @Injectable()
    export class NewsTwentyfourService {
      constructor(
        @Inject(NewsTwentyfourConfigService) private config: NewsConfig, // gets token which passed in forRoot({...})
        private http: HttpClient
      ) {}
    
      public getHeadlines(query: string = 'angular project'): Observable<any> {
        return this.http.get<Observable<any>>(`https://gnews.io/api/v3/search?q=${query}&token=${this.config.Token}`);
      }
    }
    

    Displaying API Data In Component

    Now as we create our normal components and provide service in it similarly we can show the API response in the template.

    src/lib/news-twentyfour.component.ts
    
    @Component({
      selector: 'lib-news-twentyfour',
      template: `
        <div *ngIf="news?.articles" class="news-list">
            <div *ngFor="let item of news.articles">
                <details>
                    <summary><b> <a href="{{item.url}}" target="_blank">{{item.title}}</a></b></summary>
                    <br>
                    <i>{{item.description}}</i>
                    <br>
                </details>
                <hr>
            </div>
        </div>
      `,
      styles: [`
        .news-list {margin: 20px;}
      `]
    })
    export class NewsTwentyfourComponent implements OnInit {
      public news: any;
      constructor(
        private service: NewsTwentyfourService
      ) { }
    
      public ngOnInit(): void {
        this.service.getHeadlines().subscribe(res => {
          this.news = res;
        });
      }
    }
    

    Exporting Library Services

    We can export services, model, interface etc. from one end point of library which is from src/public-api.ts

    src/public-api.ts
    
    /*
     * Public API Surface of news-twentyfour
     */
     export * from './lib/news-twentyfour.service';
     export * from './lib/news-twentyfour.component';
     export * from './lib/news-twentyfour.module';
     export * from './lib/api-config';
    
    Configurable Library Module
    .
    .

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    This site uses Akismet to reduce spam. Learn how your comment data is processed.

    We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
    Accept