简体   繁体   中英

How to receive more than one values from the backend via observables

i have the below posted service, this service connects to the backend and as a response from the backend i expect to two values x1 abd x2 i would like to know how can i modfiy the code below so to be able to receive two values

code :

public startWebService(fieldGeometry) {
var endpointURL = 
this.buildEndpointURLForLIDARWebService(fieldGeometry);
return this.httpClient.get(endpointURL)
  .subscribe((responseFromBackend)=>{
    {x1,x2} = responseFromBackend;
});
}

update

the response is from python code and the invoked webservice will return two values let's say x1 and x2.

I suggest you get the response from your backend as a JSON-object, so an object of key-value-pairs. So you can acces these attributes with their key. You don´t need to "map" them to an extra object. Because Angular is using TypeScript I would recommend to declare an interface of your object, here is an exmaple:

export interface MyObject {
    x1: number;
    x2: number;
}

When you then modify your request a little bit, you can access these values in the subscription. To say TS which attributes the response has, use your interface. And if I understand you correctly, you want to save the response in a variable of your class, so declare it first (you need the undefined or null since the http-client work asynchronous and when the page loads the response may need a bit of time):

myObject: MyObject | undefined | null;

And then in your method you subscribe to the observable, which is the return type of http-client, and save the data in your myObject variable:

public startWebService(url: string): void {
    this.httpClient.get<MyObject>(url)
        .subscribe(data => {
            myObject.x1= data.x1;
            myObject.x2= data.x2;
        });
}

Modify your service code as below to receive two space separated values from backend:

public startWebService(fieldGeometry) {
  var endpointURL = this.buildEndpointURLForLIDARWebService(fieldGeometry);
  this.httpClient.get(endpointURL).subscribe((responseFromBackend)=>{
    result = {x1: null, x2: null};
    result.x1, result.x2 = responseFromBackend.split(' ');  // assuming values are space separated
    return result;
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM