how to inject API_BASE_URL (a string) in an angular service

旧巷老猫 提交于 2019-11-30 14:57:10

问题


this autogenerated service (by NSwagStudio) needs an API_BASE_URL (InjectionToken) value in order to perform http requests how and where i can inject it?

/* tslint:disable */
//----------------------
// <auto-generated>
//     Generated using the NSwag toolchain v11.12.16.0 (NJsonSchema v9.10.19.0 (Newtonsoft.Json v9.0.0.0)) (http://NSwag.org)
// </auto-generated>
//----------------------
// ReSharper disable InconsistentNaming

import 'rxjs/add/observable/fromPromise';
import 'rxjs/add/observable/of';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/mergeMap';
import 'rxjs/add/operator/catch';

import { Observable } from 'rxjs/Observable';
import { Injectable, Inject, Optional, InjectionToken } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams, HttpResponse, HttpResponseBase, HttpErrorResponse } from '@angular/common/http';

export const API_BASE_URL = new InjectionToken<string>('API_BASE_URL');

@Injectable()
export class DocumentService {
    private http: HttpClient;
    private baseUrl: string;
    protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined;

    constructor(@Inject(HttpClient) http: HttpClient, @Optional() @Inject(API_BASE_URL) baseUrl?: string) {
        this.http = http;
        this.baseUrl = baseUrl ? baseUrl : "";
    }

    getAll(): Observable<string[] | null> {
        let url_ = this.baseUrl + "/api/Document";
        url_ = url_.replace(/[?&]$/, "");

        let options_ : any = {
            observe: "response",
            responseType: "blob",
            headers: new HttpHeaders({
                "Content-Type": "application/json", 
                "Accept": "application/json"
            })
        };

        return this.http.request("get", url_, options_).flatMap((response_ : any) => {
            return this.processGetAll(response_);
        }).catch((response_: any) => {
            if (response_ instanceof HttpResponseBase) {
                try {
                    return this.processGetAll(<any>response_);
                } catch (e) {
                    return <Observable<string[] | null>><any>Observable.throw(e);
                }
            } else
                return <Observable<string[] | null>><any>Observable.throw(response_);
        });
    }

    protected processGetAll(response: HttpResponseBase): Observable<string[] | null> {
        ...........code
        ........
        ....
    }
}

may someone give me some super quick tips about how InjectioToken works and how inject it into this service?

Angular5 - Nswag


回答1:


On the parent module create a provider for API_BASE_URL

export function getBaseUrl(): string {
  return AppConsts.baseUrl;
}

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule],
  providers: [{ provide: API_BASE_URL, useFactory: getBaseUrl }],
   bootstrap: [AppComponent]
})
export class AppModule {}

and then define a AppConsts class with static properties as such

export class AppConsts {
  static baseUrl = "your_api_base_url"; 
}

Worked for me, hope it help. This solution is based on aspnet boilerpate angular project, which for me give the best standards on architecture. I leave you here the url for the angular project + the url for this specific code.




回答2:


As mentioned above, best is to put this in your environment settings then Angular will replace the appropriate base url depending on the environment you're in, e.g. in dev:

export const environment = {

    production: false,
    apiRoot: "https://localhost:1234",
};

Then you can just use useValue in your provider (everything else removed for simplicity):

...
import { environment } from '@env/environment';

@NgModule({

    imports: [ ... ],

    declarations: [ ... ],

    providers: [

        {
            provide: API_BASE_URL,
            useValue: environment.apiRoot
        },
        ...
    ]

    exports: [ ... ]
})
export class AppModule {}

To use the @env alias as shown above you need to make an addition to the tsconfig.json as follows:

{
    ...
    "compilerOptions": {
        "baseUrl": "src",
        "paths": {
            "@env/*": [ "environments/*" ]
        },
    etc...
}

And Angular will replace the corresponding environment settings depending on the ---env flag used.




回答3:


THe best practice to put all constants in environment.ts and environment.prod.ts. Just create a new property their and import in your service. Your code will look like this:

// environment.ts
export const environment = {
  production: false,
  API_BASE_URL: "baseUrlOfApiForDevelopment",
};

// environment.prod.ts
export const environment = {
  production: false,
  API_BASE_URL: "baseUrlOfApiForProduction",
};

Now you need to import in your service to use it.



来源:https://stackoverflow.com/questions/48182290/how-to-inject-api-base-url-a-string-in-an-angular-service

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!