如何在forRoot()中注入/使用服务



我有一个angular项目,我在AppModule中导入了一个NguiMapModule,并从环境文件NguiMapModule.forRoot({apiUrl: environment.gmaps_url}),传递了一个apiUrl的值。

我的问题是如何从我的ConfigService传递gmaps_url,它从json文件

加载数据AppModule:

export function  load(http: HttpClient, config: ConfigService): (() => Promise<boolean>) {
return (): Promise<boolean> => {
return new Promise<boolean>((resolve: (a: boolean) => void): void => {
http.get('./config.json')
.pipe(
map((x: ConfigService) => {
....
config.gmaps_url=  x.gmaps_api_uri;
resolve(true);
}),
catchError((x: { status: number }, caught: Observable<void>): ObservableInput<{}> => {
if (x.status !== 404) {
resolve(false);
}
...
config.gmaps_url= 'https://maps.google.com/maps/api/js;

resolve(true);
return of({});
})
).subscribe();
});
};
}
...
providers: [
....,
{
provide: APP_INITIALIZER,
useFactory: load,
multi: true,
deps: [
HttpClient,
ConfigService
]
},
]

您可以在此Stackbitz链接中找到演示

基本上,为了提供apiUrl而不是模块文件,您需要扩展库提供的注入令牌。例如,在你的主组件app.component.ts中,我们像下面的代码一样注入token .

constructor(
@Inject(NG_MAP_CONFIG_TOKEN) apiToken: ConfigOption,
private apiService: ApiService
){
apiToken.apiUrl = this.apiService.getAPiUrl();
this.apiToken = apiToken.apiUrl;
}

我们从服务中提供了这样的api url…

import { Injectable } from "@angular/core";
@Injectable()
export class ApiService {
private apiUrl = "https://maps.google.com/maps/api/js?key=Your_APi_Key";
constructor() {}
getAPiUrl() {
return this.apiUrl;
}
}

就是这样,当你在服务中提供有效的api-key时,地图工作正常,你需要在你的谷歌账户中启用地图,以便正确地查看它。

最新更新