首页 > 解决方案 > 从服务获取数据到我的组件

问题描述

我的服务是 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 函数时,调用的是服务,我们从服务器获得响应。但是我想访问从我的服务到组件的所有变量值,例如我在构造函数和 onChange 中都尝试过

this.businessSwitchName = service.businessSwitchName // 这是未定义的

您能否让我知道如何将变量值访问到组件中。

标签: javascriptangular

解决方案


我不会在服务本身中订阅 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 businessSwitchName() {
    return this._businessSwitchName;
}

零件:

this.service.businessSwitchName

推荐阅读