如何从 angular http 客户端 (angular 5) 的结果中获取布尔值?
How to fetch a boolean value from the result in angular http client (angular 5)?
我有 Angular 5 个应用程序调用了以下服务:
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....
}
其余api如下:
@GET
@Produces("text/plain")
@Path("TripExist")
public boolean isTripExist(@QueryParam("id") String id,
@QueryParam("name") String name) {
return tripDao.isTripExist(name, id);
}
我在控制台中获取了一个正文中包含布尔值的 HttpResponse,但我不知道如何获取该值并将其分配给布尔值。
我不确定你为什么要在那里传递 observe
选项。我假设您想阅读一些 headers 或响应中的一些其他元数据。请记住这一点,因为您已完成 { observe: 'response' }
,您将获得包含很多字段的完整响应 object。但您只关心 body
字段。
所以你可以这样读:
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)
);
更新:
如果 if
条件在 subscribe
块之外,它将不起作用。订阅块中的代码 运行s 是异步的,即在 API 调用完成并收到响应之后。但是 if
条件会 运行 同步,即在 subscribe
块之前。因此,当控件达到您的 if
条件时,isExist
变量仍将是 undefined
因为它尚未初始化并且仅在 subscribe
块内初始化 运行s AFTER if
条件被执行。
我已将 if
条件移入 subscribe
块更新了我的答案。
我有 Angular 5 个应用程序调用了以下服务:
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....
}
其余api如下:
@GET
@Produces("text/plain")
@Path("TripExist")
public boolean isTripExist(@QueryParam("id") String id,
@QueryParam("name") String name) {
return tripDao.isTripExist(name, id);
}
我在控制台中获取了一个正文中包含布尔值的 HttpResponse,但我不知道如何获取该值并将其分配给布尔值。
我不确定你为什么要在那里传递 observe
选项。我假设您想阅读一些 headers 或响应中的一些其他元数据。请记住这一点,因为您已完成 { observe: 'response' }
,您将获得包含很多字段的完整响应 object。但您只关心 body
字段。
所以你可以这样读:
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)
);
更新:
如果 if
条件在 subscribe
块之外,它将不起作用。订阅块中的代码 运行s 是异步的,即在 API 调用完成并收到响应之后。但是 if
条件会 运行 同步,即在 subscribe
块之前。因此,当控件达到您的 if
条件时,isExist
变量仍将是 undefined
因为它尚未初始化并且仅在 subscribe
块内初始化 运行s AFTER if
条件被执行。
我已将 if
条件移入 subscribe
块更新了我的答案。