我对 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
当我执行 console.log 操作而不是简单地返回 response.status
时,我确实得到了预期的 200 状态代码(一个数字,而不是一个对象)。
您有什么想法为什么在返回 response.status
的值时行为不同(如此处所示)?谢谢。
最佳答案
你的做法是错误的。正确的做法如下:
首先,您从 http.get
返回映射的响应,而不是从那里订阅
。因此,您需要使用 .pipe(map(...))
而不是 subscribe
:
import { map } from 'rxjs/operators';
...
checkIfSymbolExists() {
return this.http.get(this.url, { observe: 'response' })
.pipe(
map(res => (res.status === 200))
);
}
然后从 checkIfSymbolExists
返回可观察值,然后在 onSubmit
方法中订阅
它:
onSubmit() {
this.stocks.checkIfSymbolExists()
.subscribe(res => console.log(res));
// This should print true if status is 200. false instead.
}
说明:
服务方法 checkIfSymbolExists()
的职责是为组件提供它想要的东西。所以基本上你的组件不需要知道你的服务到底从哪里获取这些数据。它只需要在订阅 checkIfSymbolExists()
Observable
时获取一个 boolean
现在,checkIfSymbolExists()
方法获得响应,并且您还添加了一个选项来观察
完整的响应。 map
只是一个用于转换响应的 Rxjs 运算符。在 map
中,我们正在做的是检查 res.status
,我们将得到它,因为我们已经通过执行 观察了响应{ 观察:'响应' }
现在,map
将返回比较运算符 ===
返回的任何内容,如果 status
将返回 true
code> 为 200
,否则为 false
。
希望这能让您更好地理解。
关于javascript - Angular 没有返回预期值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53241693/