基于UI(prod,dev,qa)的用户输入,我想选择不同的后端环境并触发各自的后端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方法。我面临的问题是,在用户API触发器上调用getData
函数之前,构造函数已经初始化并存储export const SERVICE_AUDIENCE = 'a';
的值。我必须以某种方式基于用户选择环境来动态更改SERVICE_AUDIENCE
的值,并触发不同的环境字符串。我该如何实现?