英文:
Parse Angular Http Reponse And Handle Json
问题
显示 = 响应 => {
console.log(响应);
};
导入 { Component, OnInit, OnDestroy } 自 '@angular/core';
导入 { HttpClient } 自 '@angular/common/http';
导入 { of, Subject } 自 'rxjs';
导入 { delay, tap, mergeMap, repeat, takeUntil } 自 'rxjs/operators';
export class AppComponent 实现 OnInit, OnDestroy {
私有 ngUnsubscribe = 新 主体<void>(); // 用于取消订阅的主体
构造函数(private http: HttpClient) { }
callOmni = () => of(this.pollOmni()).pipe();
显示 = 响应 => {
console.log(响应);
};
轮询 = of({}).pipe(
mergeMap(_ => this.callOmni()),
tap(this.display),
延迟(10),
重复(),
takeUntil(this.ngUnsubscribe) // 当 ngUnsubscribe 发出时取消订阅
);
pollOmni() {
返回 this.http.post<any>('http://127.0.0.1:8044/api', { call: 'getInfo' });
}
ngOnInit() {
this.poll.subscribe();
}
ngOnDestroy() {
this.ngUnsubscribe.next(); // 发出值以取消进行中的订阅
this.ngUnsubscribe.complete(); // 完成主体
}
}
英文:
I have a code that calls http post and recieves the observable notification when data is recieved .
I wish to know how to get the json respose from the server in the following function since when I try to print it it only shows the observable and not the actual json returned from the server:
display = response => {
console.log(response);
};
The complete code is :
import { Component, OnInit, OnDestroy } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { of, Subject } from 'rxjs';
import { delay, tap, mergeMap, repeat, takeUntil } from 'rxjs/operators';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnDestroy {
private ngUnsubscribe = new Subject<void>(); // Subject for unsubscribing
constructor(private http: HttpClient) { }
callOmni = () => of(this.pollOmni()).pipe();
display = response => {
console.log(response);
};
poll = of({}).pipe(
mergeMap(_ => this.callOmni()),
tap(this.display),
delay(10),
repeat(),
takeUntil(this.ngUnsubscribe) // Unsubscribe when ngUnsubscribe emits
);
pollOmni() {
return this.http.post<any>('http://127.0.0.1:8044/api', { call: 'getInfo' });
}
ngOnInit() {
this.poll.subscribe();
}
ngOnDestroy() {
this.ngUnsubscribe.next(); // Emit value to unsubscribe from ongoing subscriptions
this.ngUnsubscribe.complete(); // Complete the subject
}
}
答案1
得分: 0
错误在于 callOmni = () => of(this.pollOmni())
。
this.poolOmni
已经返回一个可观察对象,而您在其中再次使用 of
包装了一个可观察对象。
如果直接调用 poolOmni
,代码应该能正常工作。
英文:
The error is in callOmni = () => of(this.pollOmni())
.
this.poolOmni
already returns an observable, which you are wrapping in another observable with of
.
If you call directly poolOmni
the code should work fine
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论