Исходя из пользовательского ввода из пользовательского интерфейса (prod, dev, qa), я хочу выбрать другой env бэкэнда и вызвать соответствующие API бэкэнда. У меня есть домашний компонент. Оттуда я собираю пользовательскую среду, используя выпадающий список. Затем данные передаются в службу, но я не могу динамически изменять значение переменной env.
домашний компонент HTML
<select #tbchange (change)="OntbChange($event.target.value)">
<option value="choose">Select</option>
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
home.component.ts
import { element } from 'protractor';
import { SailsService } from './../services/sails.service';
import {Component, ViewChild, ElementRef, Output, EventEmitter} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, FormsModule, ReactiveFormsModule, Validator, Validators} from '@angular/forms';
import { Http, Response } from '@angular/http';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
@ViewChild('tbchange') tbchange: ElementRef;
export class HomeComponent {
onSubmit() {
console.log(this.conn.nativeElement.value);
if (this.conn.nativeElement.value === 'l2') {
if (this.myForm.value.uuid.length !== 0) {
this.uuid = this.myForm.value.uuid;
// this.testBed = this.myForm.get('testbed').value;
console.log(this.uuid);
// console.log(this.testBed);
this
.sails
.getData(this.myForm.value.uuid, this.tbchange.nativeElement.value)
.then((success) => {
const user = success.json();
this.l2UserData = user.userData;
if (this.l2UserData.length > 0) {
this.noResponse = false;
this.isL2Connection = true;
this.isL3Connection = false;
} else {
this.noResponse = true;
}
})
.catch((error) => {
this.isL2Connection = true;
this.isL3Connection = false;
console.log('Error is', error);
})
}
}
}
sails.service.ts
import {Injectable} from '@angular/core';
import {Http} from '@angular/http';
import {LogService} from './log.service';
import {environment} from '../../environments/environment';
import {ApiService} from './http/api.service';
import 'rxjs/add/operator/map';
export const SERVICE_AUDIENCE = 'a';
@Injectable()
export class SailsService extends ApiService {
constructor(http: Http,
log: LogService) {
if (!environment.services || !environment.services[SERVICE_AUDIENCE]) {
`enter code here`throw new Error('environment.service for the `enter code here`LabApiService is `enter `enter code here`enter code here`code here`missing');
}
super(SERVICE_AUDIENCE, http, log);
}
getData(uuid, env) {
return this
.get(`/api/connection/xxx?uuid=${uuid}&env=${env}`)
.toPromise()
}
env.ts
export const environment = {
production: false,
debug: {
apiCalls: '*'
},
services: {
'a': 'http://xxxx:8000',
'b': 'http://localhost:1337',
'c': 'xxxxxxx:9000'
}
};
У меня есть служба API, в которой написаны методы низкоуровневой конкатенации URL и методы REST. Проблема, с которой я сталкиваюсь, заключается в том, что перед вызовом функции getData
для пользовательского триггера API конструктор инициализируется и сохраняет значение export const SERVICE_AUDIENCE = 'a';
. Так или иначе, мне нужно динамически изменить значение SERVICE_AUDIENCE
на основе выбора пользователя env и вызвать другую строку env. Как мне этого добиться?