Angular 5/Typescript/RxJS-从可观测数据获取数据
我使用此typescript方法登录用户:Angular 5/Typescript/RxJS-从可观测数据获取数据,angular,observable,Angular,Observable,我使用此typescript方法登录用户: onSubmit() { if (this.form.valid) { this.authService.login(this.form.value).map(res => this.loginResponse = res.json).subscribe( success => { console.log('Response: ' + this.loginResponse);
onSubmit() {
if (this.form.valid) {
this.authService.login(this.form.value).map(res => this.loginResponse = res.json).subscribe(
success => {
console.log('Response: ' + this.loginResponse);
},
error => {
this.loginFailed = true;
setTimeout(()=>{
this.loginFailed = false;
}, 3000);
console.error('ERROR login.component: ' + error);
}
);
}
this.formSubmitAttempt = true;
}
实际上,我不知道如何从.map(res=>this.loginResponse=res)中获取响应数据
console.log的输出为:
Response: function () {
if (typeof this._body === 'string') {
return JSON.parse(/** @type {?} */ (this._body));
}
if (this._body instanceof ArrayBuffer) {
return JSON.parse(this.text());
}
return this._body;
}
有人知道我是如何得到带有可观察对象的响应对象的吗。
response.json
是一个函数。你需要给他们打电话
...map( res => this.loginResponse = res.json() )
如果您在Angular5上使用HttpClient而不是Http,那么我认为您可以删除.map并执行以下操作:
onSubmit() {
if (this.form.valid) {
this.authService.login(this.form.value)
.subscribe(
success => {
this.loginResponse = success;
console.log('Response: ' + success);
},
error => {
this.loginFailed = true;
setTimeout(() => {
this.loginFailed = false;
}, 3000);
console.error('ERROR login.component: ' + error);
}
);
}
this.formSubmitAttempt = true;
}
试试看
this.authService.login(this.form.value).map(res => res.json()).subscribe(
resp => {
this.loginResponse = resp;
console.log('Response: ' + this.loginResponse);
},
error=> //...
如果使用angular 5,则应使用HttpClient而不是不推荐使用的Http类。这样你就不用打电话了
.map (res=>res.json())
由于httpClient在默认情况下自动将响应转换为json格式success=>{console.log('response:'+success);},因此res.json()在最新的httpClient中不受欢迎,在使用angular 5时不再可用。是,默认情况下在angular 5中接收json