[英]Angular doesn't return the expected value
我对Angular(7)有点陌生。 我正在尝试执行HTTP请求时检索状态代码。 这是我在服务中使用的代码:
checkIfSymbolExists() {
return this.http.get(this.url, { observe: 'response' })
.subscribe(response => {
return response.status;
});
}
我在这样的组件之一的方法中使用返回值:
onSubmit() {
console.log(this.stocks.checkIfSymbolExists());
}
我期望返回一个数字,但是我有一个对象:
Subscriber {closed: false, _parent: null, _parents: null, _subscriptions: Array(1), syncErrorValue: null, …}
closed: true
destination: SafeSubscriber {closed: true, _parent: null, _parents: null, _subscriptions: null, syncErrorValue: null, …}
isStopped: true
syncErrorThrowable: true
syncErrorThrown: false
syncErrorValue: null
_parent: null
_parentSubscription: null
_parents: null
_subscriptions: null
__proto__: Subscription
当我不只是返回response.status
而是执行console.log时,确实得到了预期的200状态代码(一个数字,而不是一个对象)。
任何想法,为什么在返回如此处所示的response.status
值时为什么行为不同? 谢谢。
您做错了方法。 这是执行此操作的正确方法:
首先,您从http.get
返回映射的响应,而不是从那里进行subscribe
。 所以你需要使用.pipe(map(...))
而不是subscribe
:
import { map } from 'rxjs/operators';
...
checkIfSymbolExists() {
return this.http.get(this.url, { observe: 'response' })
.pipe(
map(res => (res.status === 200))
);
}
然后,从checkIfSymbolExists
返回observable,然后在onSubmit
方法中对其进行subscribe
:
onSubmit() {
this.stocks.checkIfSymbolExists()
.subscribe(res => console.log(res));
// This should print true if status is 200. false instead.
}
说明:
服务方法checkIfSymbolExists()
的责任是为Component提供所需的内容。 因此,基本上,您的组件不需要知道您的服务从何处确切地获取此数据。 订阅checkIfSymbolExists()
返回的Observable
,只需要获取一个boolean
即可
现在, checkIfSymbolExists()
方法获取响应,并且您还添加了一个选项来observe
完整的响应。 map
只是一个Rxjs运算符,它将转换响应。 在map
,我们正在做的是检查res.status
,这是因为我们已经observe
d的响应,方法是执行{ observe: 'response' }
res.status
{ observe: 'response' }
现在, map
将返回比较运算符===
返回的true
如果status
为200
,则返回true
,否则返回false
。
希望这能给您更好的理解。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.