我在下面将我的服务作为PortAllocationService
@Injectable({
providedIn: 'root'
})
export class PortAllocationService {
businessSwitchName: any;businessSwitchIp: any;businessSwitchportName: any;
businessSwitchNodeId: any;routerName: any;routerIp: any;routerDetailsportName: any;
routernodeID: any;aggSwitchName: any;aggSwitchPort: any;aggNodeIP: any;
aggNodeId: any;serviceName: any;convertorDetails: any;handoffPort: any;qosLoopingPort: any;
constructor(private http:HttpClient) { }
portService(da){
return this.http.post(url.portAllocationUrl , da).
subscribe ((response:any) => {
//Port Allocation response is mapped here
console.log(response);
// businessSwitchDetails
this.businessSwitchName = response.businessSwitchDetails.nodeName;
this.businessSwitchIp = response.businessSwitchDetails.nodeIP;
});
}
和我的组件如下
export class WimaxFormComponent {
data : any = {};
btsIp :any; vCategory:any;nVlan:any;
businessSwitchName:any;businessSwitchIp:any;businessSwitchportName:any;
routerName:any;routerIp:any;aggSwitchName:any;aggSwitchPort:any;
routerDetailsportName:any;routernodeID:any;aggNodeIP: any;aggNodeId: any;
businessSwitchNodeId: any;serviceName: any;convertorDetails: any;
handoffPort: any;qosLoopingPort: any;
serviceId: any;serviceType: any;customerName: any;
vReservedValue:boolean;cVlan: string;sVlan: any;
path: string;
constructor(
private service: PortAllocationService){
}
onChange(){
let portAllocationData = {
"serviceAttribute": {
"serviceType": this.serviceType,
"category": "category",
"name": this.serviceId
},
"btsIp": this.btsIp
}
console.log(portAllocationData);
this.service.portService(portAllocationData);
}
当我调用onChange函数时,将调用该服务,并且我们从server获得响应。但是我想从服务访问组件的所有变量值,例如我在构造函数和onChange中都尝试过
this.businessSwitchName = service.businessSwitchName // //未定义
请让我知道如何将变量值访问到组件中。
答案 0 :(得分:1)
我不会在服务本身中订阅API调用,而是仅返回http.post()
进行的观察。然后将订阅移动到组件本身:
服务:
portService(da){ return this.http.post(url.portAllocationUrl , da) });
组件:
this.service.portService(portAllocationData).subscribe(response => {
// Do stuff with the response here
});
但是,如果您真的想将变量保留在服务中,则可以将API调用放在服务的构造函数中,更改服务中的字段以下划线(或其他一些本地/私有标识符)开头然后为要访问的每个变量提供get方法。
服务:
get businessSwitchName() {
return this._businessSwitchName;
}
组件:
this.service.businessSwitchName