如何在角度服务中注入API_BASE_URL(字符串)

ale*_*lex 10 nswag angular

这个自动生成的服务(由NSwagStudio)需要一个API_BASE_URL(InjectionToken)值才能执行http请求我可以注入的方式和位置?

/* 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
        ........
        ....
    }
}
Run Code Online (Sandbox Code Playgroud)

有人可以给我一些关于InjectioToken如何工作以及如何将其注入此服务的超快速提示?

Angular5 - Nswag

Gui*_*oli 12

在父模块上为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 {}
Run Code Online (Sandbox Code Playgroud)

然后使用静态属性定义AppConsts类

export class AppConsts {
  static baseUrl = "your_api_base_url"; 
}
Run Code Online (Sandbox Code Playgroud)

为我工作,希望它有所帮助.该解决方案基于aspnet boilerpate角度项目,这为我提供了最佳的架构标准.我在这里留下角度项目的网址+此特定代码的网址.


Mat*_*att 7

如上所述,最好将其放在您的环境设置中,然后Angular会根据您所处的环境(例如在dev中)替换相应的基本url:

export const environment = {

    production: false,
    apiRoot: "https://localhost:1234",
};
Run Code Online (Sandbox Code Playgroud)

然后,您可以在提供程序中使用useValue(为简单起见,删除了所有其他内容):

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

@NgModule({

    imports: [ ... ],

    declarations: [ ... ],

    providers: [

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

    exports: [ ... ]
})
export class AppModule {}
Run Code Online (Sandbox Code Playgroud)

要使用如上所示的@env别名,您需要对tsconfig.json进行如下添加:

{
    ...
    "compilerOptions": {
        "baseUrl": "src",
        "paths": {
            "@env/*": [ "environments/*" ]
        },
    etc...
}
Run Code Online (Sandbox Code Playgroud)

Angular将根据使用的--env标志替换相应的环境设置。


Jep*_*ppe 2

要设置和使用注入令牌,您需要执行以下操作:

  • 创建注入令牌以便可以使用它(nswag 会为您完成此操作)
  • 提供注入令牌的值
  • 在您的服务(例如 nswag 生成的客户端)、组件等中使用注入令牌。
import { InjectionToken, NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { API_BASE_URL } from 'generated-nswag-client';

export function getBaseUrl() {
    return document.getElementsByTagName('base')[0].href;
}

@NgModule({
    ...,
    providers: [
        { provide: API_BASE_URL, useFactory: getBaseUrl, deps: [] },
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }
Run Code Online (Sandbox Code Playgroud)

现在,Nswag 以及您的所有组件和服务可以期望从依赖注入系统接收与令牌相对应的值:

@Injectable()
export class MyUrlAwareService {
    apiBaseUrl = inject(API_BASE_URL);
}
Run Code Online (Sandbox Code Playgroud)