简体   繁体   English

了解Angular2项目结构

[英]Understanding Angular2 project structure

I'm a bit confused around an typescript/Angular2 project structure I've downloaded as a base code in order to extend it. 我对于为扩展它而下载的基本typescript/Angular2项目结构有些困惑。

It's related with how providers are initialized and provided on angular2. 它与如何在angular2上初始化和提供提供程序有关。

Currently, this is AppModule code: 当前,这是AppModule代码:

import { ENV_PROVIDERS } from './environment';
import { APP_RESOLVER_PROVIDERS } from './app.resolver';

// Application wide providers
const APP_PROVIDERS = [
  ...APP_RESOLVER_PROVIDERS,
  AppState,
  AppConfig
];
@NgModule({
  bootstrap: [ App ],
  declarations: [ ... ],
  imports: [ ... ],
  providers: [
    ENV_PROVIDERS,
    APP_PROVIDERS
  ]
})
export class AppModule {

As you can see there are two items: ENV_PROVIDERS and APP_PROVIDERS provided as an array of providers. 如您所见,有两个项目: ENV_PROVIDERSAPP_PROVIDERS作为提供程序数组提供。

app.resolver.ts : app.resolver.ts

import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';

@Injectable()
export class DataResolver implements Resolve<any> {
  constructor() {

  }
  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    return Observable.of({ res: 'I am data'});
  }
}

// an array of services to resolve routes with data
export const APP_RESOLVER_PROVIDERS = [
  DataResolver
];

environtment.ts : environtment.ts

// Angular 2
// Environment Providers
let PROVIDERS: any[] = [
  // common env directives
];

if ('production' === ENV) {
  PROVIDERS = [
    ...PROVIDERS,
    // custom providers in production
  ];

} else {
  // Development
  PROVIDERS = [
    ...PROVIDERS,
    // custom providers in development
  ];

}

export const ENV_PROVIDERS = [
  ...PROVIDERS
];

By other hand, I'm using a library which is a REST client implementation. 另一方面,我使用的是REST客户端实现的库。 This library has an ApiModule class with a forConfig method I'm not able to figure out how to use it. 这个库有一个带有forConfig方法的ApiModule类,我无法弄清楚如何使用它。 It's returning an object setting ngModule and providers ... 它返回一个对象设置ngModuleproviders ...

@NgModule({
  imports:      [ CommonModule, HttpModule ],
  declarations: [],
  exports:      [],
  providers:    [ UsersService ]
})
export class ApiModule {
    public static forConfig(configuration: Configuration): ModuleWithProviders {
        return {
            ngModule: ApiModule,
            providers: [ {provide: Configuration, useValue: configuration}]
        }
    }
}

where Configuration is: 其中Configuration是:

export interface ConfigurationParameters {
    apiKey?: string;
    username?: string;
    password?: string;
    accessToken?: string;
    basePath?: string;
}

export class Configuration {
    apiKey: string;
    username: string;
    password: string;
    accessToken: string;
    basePath: string;


    constructor(configurationParameters: ConfigurationParameters = {}) {
        this.apiKey = configurationParameters.apiKey;
        this.username = configurationParameters.username;
        this.password = configurationParameters.password;
        this.accessToken = configurationParameters.accessToken;
        this.basePath = configurationParameters.basePath;
    }
}

I'd like to know according to this structure how I'm able to add my custom providers and set for example basePath property. 我想根据这种结构来了解如何添加自定义提供程序并设置例如basePath属性。

This an example of UserService : 这是UserService的示例:

@Injectable()
export class UsersService {
    protected basePath = 'http://localhost/commty/cmng';
    public defaultHeaders: Headers = new Headers();
    public configuration: Configuration = new Configuration();

    constructor(protected http: Http, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) {

I hope I've explained so well. 我希望我已经解释得很好。

I see that you are using the typescript-angular2 client for the petstore. 我看到您正在为petstore使用typescript-angular2客户端。 I myself love swagger and am happy people are using it! 我自己喜欢招摇,很高兴人们正在使用它!

Anyhow to answer your question if you want to set basePath without having to use that configuration in forConfig you can simply do this 如果您想设置basePath而不用在forConfig中使用该配置,无论如何回答您的问题,您都可以简单地做到这一点

in AppModule: 在AppModule中:

...
@NgModule({
  bootstrap: [ App ],
  declarations: [ ... ],
  imports: [ ... ],
  providers: [
    ENV_PROVIDERS,
    APP_PROVIDERS,
    {provide: BASE_PATH, useValue: 'http:your.url.awesome'}
  ]
})
export class AppModule {

This will utilize the injected value for all of the modules that use that @Inject keyword which all of the swagger api's do 这将对所有使用该@Inject关键字的模块进行注入,所有swagger api都会这样做

You could also use this if you are bootstrapping by hand: 如果手动启动,也可以使用以下命令:

in BootstrapFile: 在BootstrapFile中:

    bootstrap(AppComponent, [
        { provide: BASE_PATH, useValue: 'https://your-web-service.com' },
    ]);

If you want to take advantage of using the configuration object you'd change to this: 如果您想利用配置对象,可以将其更改为:

import { ApiModule, Configuration } from "module-library-name";
...
const myAppConfig = new Configuration({
 ...
 basePath: 'https://your-web-service.com'
});
@NgModule({
  bootstrap: [ App ],
  declarations: [ 
  ApiModule.forConfig(myAppConfig);
  ],
  imports: [ ... ],
  providers: [ ... ]
})
export class AppModule {

if you wanted to dynamically determine your configuration before the app starts and then pas that along into the app module you'd use a provider for APP_INITIALIZER which I can add if this answer is still needed. 如果您想在应用启动之前动态确定配置,然后将其粘贴到应用模块中,则可以使用APP_INITIALIZER提供程序,如果仍然需要此答案,我可以添加它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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