×
  • 建立和发布Angular库(v10)的最佳方法

  • 02 –制作可配置的库模块

    课程清单

    在本课程中,我们将介绍如何创建可配置的库模块。例如,在本课程中,我们将创建一个显示来自某些外部API的新闻的库,但该API必须具有令牌。
    因为我们正在创建一个可通过NPM软件包管理器在全球范围内使用的库,因此我们必须接受用户端的令牌。

    可配置的库模块

    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.
    所以在我们的库文件夹里面 src / lib / 将创建一个名为 api-config.ts

    src / lib / api-config.ts
    
    import { 注入令牌 } from '@angular/core';
    export interface 新闻Config {
      Token: string;
    }
    export const 新闻TwentyfourConfigService = new 注入令牌<NewsConfig>('NewsConfig');
    

    了解更多 注入令牌
    The next thing are we going to do is we will use this Token from 新闻TwentyfourConfigService 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 新闻TwentyfourModule {
      // 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 新闻TwentyfourConfigService

    src / lib / news-twentyfour.module.ts
    
    @NgModule({...})
    export class 新闻TwentyfourModule {
      static forRoot(config: 新闻Config): ModuleWithProviders {
        return {
          ngModule: 新闻TwentyfourModule,
          providers: [
            新闻TwentyfourService, // service for news API
            { provide: 新闻TwentyfourConfigService, useValue: config } // service for configuring token in API
          ]
        };
      }
    }
    

    因此,无论您在哪里导入模块,都可以在其中传递令牌。

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

    在服务中使用配置值

    Till now we have created a configurable Library Module but for using those values we have to also inject the service i.e. 新闻TwentyfourConfigService into the service file.
    对于本课程,我们使用 gnews.io API

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

    在组件中显示API数据

    现在,当我们创建常规组件并在其中提供服务时,我们可以在模板中显示API响应。

    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 新闻TwentyfourComponent implements OnInit {
      public news: any;
      constructor(
        private service: 新闻TwentyfourService
      ) { }
    
      public ngOnInit(): void {
        this.service.getHeadlines().subscribe(res => {
          this.news = res;
        });
      }
    }
    

    导出图书馆服务

    我们可以从库的一个端点导出服务,模型,接口等 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';
    
    可配置的库模块
    .
    .
  • 启用通知    不用了,谢谢