问题
I have Angular 5 app with the following service call:
let isExist: boolean;
this.http.get<Boolean>(`${this.baseUrl}/Trips/TripExist`, {
headers: new HttpHeaders({ 'Accept': 'text/plain', 'Content-Type': 'text/plain' }),
params: {id: id, name: name},
observe: 'response'
}).subscribe(
data => { isExist = data.body;
console.log(data);
},
err => console. error(err)
);
if (isExist == true) {
Console....
}
The rest api is as follow:
@GET
@Produces("text/plain")
@Path("TripExist")
public boolean isTripExist(@QueryParam("id") String id,
@QueryParam("name") String name) {
return tripDao.isTripExist(name, id);
}
I'm getting in the console an HttpResponse with the boolean value in the body but I don't know how to fetch the value and assign it to a boolean value.
回答1:
I'm not sure why you're passing the observe
option there. I'm assuming that you want to read some headers or some other meta data on the response. Keeping that in mind, since you've done { observe: 'response' }
, you'll get the complete Response object with a lot of fields in it. But all you're concerned about is the body
field.
So you can read it like this:
let isExist: boolean;
this.http.get(`${this.baseUrl}/Trips/TripExist`, {
headers: new HttpHeaders({
'Accept': 'text/plain',
'Content-Type': 'text/plain'
}),
params: {
id: id,
name: name
},
observe: 'response'
}).subscribe(
data => {
isExist = data.body; // HERE data.body will have the boolean that you're looking for.
console.log(data);
console.log(isExist);
if (isExist === true) { console.... }
},
err => console.error(err)
);
UPDATE:
It won't work if the if
condition is outside the subscribe
block. The code inside the subscribe block runs asynchronously, i.e. after the API call is done with and the response is received. But the if
condition would run synchronously, i.e. before the subscribe
block. So when the control reaches your if
condition, the isExist
variable would still be undefined
as it hasn't been initialized and only gets initialized inside the subscribe
block which runs AFTER the if
condition is executed.
I've updated my answer with the if
condition moved inside the subscribe
block.
来源:https://stackoverflow.com/questions/53466539/how-to-fetch-a-boolean-value-from-the-result-in-angular-http-client-angular-5