通過使用 Nx。創建了多個應用程式,每個應用程式都有自己的環境,具有不同的 API URL。Nx Workspace 庫有一些在所有應用程式之間使用的共享服務。但是在組件中注入服務時需要傳遞 environment-api-url。
@Component({
standalone: true,
imports: [
ReactiveFormsModule,
FormsModule,
HttpClientModule
],
providers: [AuthenticationService],
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css'],
})
export class LoginComponent implements OnInit {
ngOnInit() {}
}
我們可以這樣通過嗎
providers: [AuthenticationService<environment>]
或任何其他方式來實作它。
先進的贊賞!
uj5u.com熱心網友回復:
您可以創建另一個名為app-config. 然后在里面創建一個index.ts檔案(lib/app-config/src/lib/config/index.ts)。
在您的 index.ts 中匯出一個 InjectionToken。
import { InjectionToken } from '@angular/core';
export const APP_CONFIG = new InjectionToken('App Config');
將此添加到Providers您的LoginComponent.
import { APP_CONFIG } from '@YourWorkspaceName/app-config';
providers: [
{
provide: APP_CONFIG,
useValue: environment,
},
AuthenticationService
]
然后在您的AuthenticationService注入APP_CONFIG中訪問您的環境變數。
import { APP_CONFIG } from '@YourWorkspaceName/app-config';
export class AuthenticationService {
private readonly url: string = this.appConfig.authServiceUrl;
constructor(
private http: HttpClient,
@Inject(APP_CONFIG) private appConfig: any
) {}
login(EmailAddress: string, Password: string): Observable<any> {
return this.http.post<{ authToken: string }>(`${this.url}/login`, {
EmailAddress,
Password,
});
}
}
希望你覺得這很有幫助。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/510201.html
上一篇:呼叫API時查詢引數編碼
