[英]How to wait until subscribe finishes | Angular 9
我的任務是在match.service.ts中創建一個方法,該方法將從服務器獲取數據(比賽),對其進行必要的操作並返回結果。
比賽.service.ts :
getContests() {
let id = IDs.contests.getAll;
let body = {
...
};
let result;
this.wsservice.send(id, body);
this.wsservice.on<any>(IDs.contests.getAll)
.subscribe((msg) => {
console.log('msg', msg);
if (!msg['code']) {
result = msg;
console.log('contests msg', result);
this.contests = result.map(contest => {
return new Contest({
id: contest.id,
name: contest.name || "Нет названия",
description: contest.description,
contestTasks: contest.tasks || []
});
});
}
else {
result = "Error";
}
});
return result;
}
我需要等到this.wsservice.on(IDs.contests.getAll)訂閱完成,然后從中返回結果。 websocket.service.ts 中的方法:
public send(eventId: any, data: any = {}): void {
console.log('SEND');
let that = this;
if (eventId && this.isConnected && this.websocket$) {
data['id'] = eventId;
this.websocket$.next(data);
} else {
setTimeout(function() {
that.send(eventId, data);
}, 500);
console.log('Still connecting, resending messsage...');
}
}
public on<T>(eventId: any): Observable<T> {
console.log(eventId);
if (eventId) {
return this.wsMessages$.pipe(
filter((message: IWsMessage<T>) => message.id === eventId),
map((message: IWsMessage<T>) => message.result ? message.result : message.error)
);
}
}
改進我的評論。
你應該返回一個可觀察的。 您可以使用
getContests() {
....
return this.wsservice.on<any>(IDs.contests.getAll).pipe(
//we don't want the response else
switchMap(msg)=>{
..do something with the msg..
//create an object
const contest= new Contest({
...});
//we need return an observable, we use rxjs operator 'of'
return of(contest)
}
)
或使用 map
getContests() {
....
return this.wsservice.on<any>(IDs.contests.getAll).pipe(
//we are going to transform the response
map(msg)=>{
..do something with the msg..
//create an object
const contest= new Contest({
...});
return contest; //<--see that return simple the object
}
)
看到返回一個可觀察的,所以在你的組件中訂閱
this.service.getContests().subscribe(res=>{
//here you has the object contest
console.log(res)
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.